如何使用regex搜索和删除字符串?

2024-09-26 22:53:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一根线:

'<div class="hotels-hotel-review-about-with-photos-Reviews__subratingRow--2u0CJ"><span class="ui_bubble_rating bubble_45"></span><div class="hotels-hotel-review-about-with-photos-Reviews__subratingLabel--H8ZI0">Location</div></div>'

我想提取bubble_后面的数值,也就是45。你知道吗

我试过:

rating = re.search('bubble_(\d+)', str(line)).group(0)
rating = re.sub("bubble_" , '', rating)

我的代码可以工作,但我想知道是否有一个更python是这样做的。(而不是两行代码,只有一行!) 谢谢


Tags: 代码divrewithhotelreviewclassabout
3条回答

这个怎么样?你知道吗

rating = re.sub("bubble_" , '', re.search('bubble_(\d+)', str(line)).group(0))

老实说,我宁愿写在2行,以提高可读性。你知道吗

使用此正则表达式:

(?<=bubble_)(\d+)

使用一行:

rating = re.search('(?<=bubble_)(\d+)', str(line)).group(0)

只需将.group(0)替换为.group(1)即可访问捕获组的内容:

line = '<div class="hotels-hotel-review-about-with-photos-Reviews__subratingRow 2u0CJ"><span class="ui_bubble_rating bubble_45"></span><div class="hotels-hotel-review-about-with-photos-Reviews__subratingLabel H8ZI0">Location</div></div>'
rating = re.search('bubble_(\d+)', str(line)).group(1)
print rating

输出:

45

相关问题 更多 >

    热门问题