Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在尝试使用正则表达式从字符串中过滤值,例如<a href=""/>从标签中过滤掉 URL 。
<a href=""/>
<a href="http://www.example.com">
我查看了re库,应该匹配字符串的正则表达式应该是
r'<a href="(.*)">'
现在将此值保存到变量中的最佳方法是什么?
您不应该使用正则表达式解析 html,但既然您说这只是一个示例…… 如果您希望总能找到匹配项:
try: foo = re.search(r'<a href="(.*)">', text).group(1) except AttributeError: foo = None
如果你不知道它是否匹配:
match = re.search(r'<a href="(.*)">', text) if match: foo = match.group(1) else: foo = None