17
>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None

in Kiki that matches the test at the end of the s. What do I miss? (I tried re.compile(r'test$') as well)

mgilson
  • 300,191
  • 65
  • 633
  • 696
tetris555
  • 335
  • 1
  • 2
  • 8

3 Answers3

33

Use

match1 = reg1.search(s)

instead. The match function only matches at the start of the string ... see the documentation here:

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

Useless
  • 64,155
  • 6
  • 88
  • 132
2

Your regex does not match the full string. You can use search instead as Useless mentioned, or you can change your regex to match the full string:

'^this is a test$'

Or somewhat harder to read but somewhat less useless:

'^t[^t]*test$'

It depends on what you're trying to do.

iwein
  • 25,788
  • 10
  • 70
  • 111
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 are 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