所以我有以下格式的数据:
<Category: XXX -
或
<Category: XXX</b>
<小时/>
我只想保留“xxx”,但只能保留 ('XXX','') 或 ('') 或其他不需要的变体。
我不想使用 beautiful soup,我在使用 anaconda 包管理器下载它时遇到问题
<小时/>添加 - 我的尝试
'Category: ([^<]+)</b'
当
时会产生['xxx']<Category: XXX</b>
<小时/>
'Category: ([^<]+) &n'
当
时会产生['xxx']<Category: XXX
我想我做了类似的事情
'Category: ([^<]+)(</b| &n)'
结果
[('XXX', '</b')]
或
[('XXX', ' &nb')]
最佳答案
>>> import re
>>> re.match('<Category:\s(\w+)', "<Category: XXX</b>").group(1)
'XXX'
>>> re.match('<Category:\s(\w+)', "<Category: XXX - ").group(1)
'XXX'
或使用findall
:
>>> import re
>>> re.findall('<Category:\s(\w+)', "<Category: XXX - ")[0]
'XXX'
>>> re.findall('<Category:\s(\w+)', "<Category: XXX</b>")[0]
'XXX'
\s
匹配任何空白字符。\w
匹配任何非字母数字字符;这相当于集合[^a-zA-Z0-9_]
。\w+
匹配一个或多个非字母数字字符。(...)
是一个捕获组:
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed
参见documentation了解更多信息。
关于python - 使用 python 正则表达式匹配但不包括其中之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18340765/