Skip to main content
 首页 » 编程设计

python之使用正则表达式省略数字

2025年05月04日23zfyouxi

这恐怕简单得吓人,但我无法让它发挥作用(而且我无法通过搜索找到答案)。我正在为所有斜体字词抓取网站(我想要的是两个词组——它们是二项式科学名称),但我不希望返回任何数字。

我使用的正则表达式:<i>(.+?)</i>

效果很好,但它拉动了数字。我想用 \D会工作,但事实并非如此。我做错了什么?

请您参考如下方法:

Yes, I basically want to strip integers from any string inside the tags.

Python 的 re.findall 循环遍历你的匹配替换数字字符应该适合你。

pattern = re.compile(r'(?<=<i>).*?(?=</i>)') 
 
for names in re.findall(pattern, htmltext): 
    print re.sub(r'[0-9]', '', names) 

要查找不包含数字的匹配项:

matches = re.findall(r'(?<=<i>)[^0-9]*(?=</i>)', htmltext) 
print matches