0

Here's the code:

pattern = re.compile(r'ea') 
match = pattern.match('sea ea')
if match:
    print match.group()

the result is null. But when I change the code to pattern = re.compile(r'sea'), the output is "sea"

Could anyone give me an explanation?

p.s. Btw, What I want is to retrieve the "#{year}" from string "select * from records where year = #{year}", plz give me an usable regex. Thanks in advance!

Summary:

Thanks to ALL of u, I find it in the document of python with your instruction. since I can select only one most appropriate answer, I just give it to the one who answered most quickly. Thx again.

0

3 Answers 3

2

pattern.match is anchored at the beginning of the string.

You need pattern.search.

From the documentation:

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

Sign up to request clarification or add additional context in comments.

Comments

2

You mean to use search, not match. match will match the regular expression only if it is at the start of the string.

pattern = re.compile(r'ea') 
match = pattern.search('sea ea')
if match:
    print match.group()

Comments

0

match just matches, it doesn't search for things. This does:

>>> pattern = re.compile(r'(#{\w+})') 
>>> pattern.split('select * from records where year = #{year}')
['select * from records where year = ', '#{year}', '']

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.