Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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"'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...