Home > Software engineering >  How to use Python regex pattern matching with re.findall(pattern, string)?
How to use Python regex pattern matching with re.findall(pattern, string)?

Time:10-31

I need to match to the strings "Johnson" and "Jackson", but not the string "Jason." Using Python, I need to use the function findall in the RegEx library.

I tried:

a = "Jackson, Johnson, Jason"
b = re.findall("J*\w{2}*son", a)

and it did not work! If there is anyone that can help, i would very much appreciate it!

CodePudding user response:

findall only works with a string as input not a list.

You probably want to use map and re.match or re.search for example:

Also your regex has multiple repeat symbols in it and needs some tuning, this one seems to work J\w{3}son

import re
a = ["Jackson", "Johnson", "Jason"]
c = list(map(lambda x: re.search("J\w{3}son",x), a))
print([i.string for i in c if i])

output:

['Jackson', 'Johnson']

Update if your input type is just a string then your original expression was fine you just need to change the regex to the example above

import re
a = "Jackson Johnson Jason"
b = re.findall("J\w{3}son", a)
print(b)

output:

['Jackson', 'Johnson']
  • Related