如何匹配此字符串中的价格?
<div id="price_amount" itemprop="price" class="h1 text-special">
$58
</div>
我希望这个字符串中的$ 58,怎么做?这就是我所要做的,但不起作用:
regex = r'<div id="price_amount" itemprop="price" class="h1 text-special">(.+?)</div>'
price = re.findall(regex, string)
答案 0 :(得分:2)
你真的不应该使用regex
来解决这个特殊问题。查看Python的XML / HTML解析库。
话虽如此,您的正则表达式只是缺少新行的匹配项,因此您需要在开始标记之后和结束标记之前添加\s*
。
import re
string="""
<div id="price_amount" itemprop="price" class="h1 text-special">
$58
</div>
"""
regex = r'<div id="price_amount" itemprop="price" class="h1 text-special">\s*(.+?)\s*</div>'
price = re.findall(regex, string)
print price
答案 1 :(得分:2)
尝试仅捕获<div></div>
标记之间的价格
import re
str=('<div id="price_amount" itemprop="price" class="h1 text-special">'
'$58'
'</div>')
regex = r'<div id="price_amount" itemprop="price" class="h1 text-special">([^<]*?)</div>'
price= re.search(regex, str)
price.group(1) # => '$58'
([^<]*?)
此代码将捕获<
零次或多次的任何字符,并将捕获的字符存储到一个组中group1
)。?
后跟{{ 1}}表示非贪婪的匹配。