-1

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 ?

3

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.