24

I feel kind of stupid but it does not work:

import re

a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2"

print re.match(ur'/(wekjb|ABB)/',a)
if re.match(ur'/(wekjb|ABB)/',a):
    print 'success'

I have the ur' if the user given a is unicode. I want to print success if wekjb or ABB is in the string but I always get None as the result of the match.

Diolor
  • 13,181
  • 30
  • 111
  • 179
  • 8
    Try using `.search()` instead of `.match()`. `.match()` is anchored to the start of the string. And there are no instances of `/` in `a` - why are there instances of `/` in your regexp? – Tim Peters Nov 09 '13 at 01:21

2 Answers2

72

re.match is implicitly anchored to the start of the string. If you want to search a string for a substring that can be anywhere within it, then you need to use re.search:

import re

a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2"

print re.search(ur'(wekjb|ABB)',a).group()
if re.search(ur'(wekjb|ABB)',a):
    print 'success'

Output:

wekjb
success

Also, Python Regexes do not need to have a / at the start and end.

Lastly, I added .group() to the end of the print line because I think this is what you want. Otherwise, you'd get something like <_sre.SRE_Match object at 0x01812220>, which isn't too useful.

  • 1
    I don't think it's the case that "`re.match` looks for an _exact_ match." Rather, it's that `match()` is implicitely anchored at the beginning of line. But maybe I'm just dicing semantics there..? The expression `ur'.*(wekjb|ABB)',a` works just fine. – Travis Griggs Nov 09 '13 at 01:51
  • 2
    @TravisGriggs - No, that's fine. It's better to be technical. I adjusted my post and added a link for further reference. –  Nov 09 '13 at 01:56
0

It's because of that match method returns None if it couldn't find expected pattern, if it find the pattern it would return an object with type of _sre.SRE_match .

So, if you want Boolean (True or False) result from match you must check the result is None or not!

You could examine texts is matched or not somehow like this:

string_to_evaluate = "Your text that needs to be examined"
expected_pattern = "pattern"

if re.match(expected_pattern, string_to_evaluate) is not None:
    print("The text is as you expected!")
else:
    print("The text is not as you expected!")
AbdolHosein
  • 528
  • 4
  • 15