Home > Back-end >  The sentence must contain words and numeric characters
The sentence must contain words and numeric characters

Time:04-21

I want to get a sentence that has both words and numeric characters. I tried many sources but still stuck.

My code:

eg_str= ['add - James Smith, Flat 7 118 Black-horse, MA-021-30', 'add - Alice, Derrick Street']
reg = re.findall(r'([a-z]{3,}[\s][-][\s][A-Z 0-9 a-z ,\-] )', str(eg_str))
print(reg)

Output I get:

['add - James Smith, Flat 7 118 Black-horse, MA-021-30', 'add - Alice, Derrick Street'] 
                  

Expected output:

['add - James Smith, Flat 7 118 Black-horse, MA-021-30']

Can anyone help me what I'm missing here?

Update: Example pattern : 'add - James Smith, Flat 7 118 Black-horse, MA-021-30 - 1234'. I want to get exactly this pattern from the list of inputs I have. The regex should omit "ad - Alice, Derrick Street" and "add - Alice, Derrick Street - 1314". Is there a possibility to group expression to match the pattern as follows,

  1. 3 or more letters #add
  2. - # -
  3. Sentence with alphabets and numbers including, - #James Smith, Flat 7 118 Black-horse, MA-021-30
  4. - # -
  5. 4 or more digits #1234

CodePudding user response:

You may match on the regex pattern:

[A-Z].*[0-9]|[0-9].*[A-Z]

Python script:

eg_str = ['add - James Smith, Flat 7 118 Black-horse, MA-021-30', 'add - Alice, Derrick Street']
matches = [x for x in eg_str if re.search(r'[A-Z].*[0-9]|[0-9].*[A-Z]', x, flags=re.I)]
print(matches)  # ['add - James Smith, Flat 7 118 Black-horse, MA-021-30']

CodePudding user response:

It looks like you could just access the first item in the list to get the answer you want.

print(eg_str[0])

If you are trying to apply the regex to each item in the list then you should loop through the list and then apply the correct regex to it.

eg_str= ['add - James Smith, Flat 7 118 Black-horse, MA-021-30', 'add - Alice, Derrick Street']

temp = []
for item in eg_str: 
    reg = re.findall(r'([A-Z].*[0-9]|[0-9].*[A-Z])', item)
    temp.append(reg)
print(temp)

This would return:

[['James Smith, Flat 7 118 Black-horse, MA-021-30'], []]

You can learn more about regex here:

https://regexr.com/

https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285

You can learn more about how to use lists and access elements of a list here: https://www.geeksforgeeks.org/python-list/

  • Related