Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

regex - Python findall not matching correctly

I am trying to match an html a tag with regex as shown below:

string = r'<a class="article_txt" href="/store">abcd</a>'
pattern = r'<[s]*a[s]*(class[s]*=[s]*"article_txt")[s]*.*?</a>'

tags = re.search(pattern, string)
print(tags.group())

with the expected output: <a class="article_txt" href="/store">abcd</a>

while this gives me the correct answer, I however, need to search multiple matches in a file. so I tried using re.findall. But to my surprise, this doesn't match correctly.

The code for this specific example is:

string = r'<a class="article_txt" href="/store">abcd</a>'
pattern = r'<[s]*a[s]*(class[s]*=[s]*"article_txt")[s]*.*?</a>'

tags = re.findall(pattern, string)
print(tags)

returns this mysterious output: ['class="article_txt"']

why did findall only match the group in my regex?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put the parens in correct locations (around the desired pattern). This alone fixes the issue. You can also simplify your regex, use raw string for regex only, which improves the code (but does not affect the output in this case):

import re
string = '<a class="article_txt" href="/store">abcd</a>'
pattern = r'(<as+class="article_txt".*?</a>)'

tags = re.findall(pattern, string)
print(tags)
# ['<a class="article_txt" href="/store">abcd</a>']

Your original code had parentheses around only part of the desired pattern, like so: (class[s]*=[s]*"article_txt"). This created a capture group. Because re.findall returns captured pattern, you got only that part of the string: 'class="article_txt"'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...