-2

I find this behavior slightly strange:

pattern = re.compile(r"test")
print pattern.match("testsda") is not None
True
print pattern.match("astest") is not None
False

So, when the string doesn't match the pattern at its end, everything is fine. But when the string doesn't match the pattern at its beginning, the string doesn't match the pattern anymore.

By comparison, grep succeeds in both cases:

echo "testsda" | grep  test
testsda
echo "adtest" | grep  test
adtest

Do you know why this is happening ?

Razvan
  • 9,925
  • 6
  • 38
  • 51

1 Answers1

4

re.match is designed to only match at the start of a string. As the docs state:

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).

If you use re.search, you should be fine:

import re

pattern = re.compile(r"test")
print pattern.search("testsda") is not None
print pattern.search("astest") is not None

prints

True
True
asongtoruin
  • 9,794
  • 3
  • 36
  • 47