python - 如何在 python 中修复这个正则表达式?

标签 python regex

我想处理一些像这样打印出来的字符串日期

'node0, node1 0.04, node8 11.11, node14 72.21\n'
'node1, node46 1247.25, node6 20.59, node13 64.94\n'

我想在这里找到所有的 float ,这是我使用的代码

for node in nodes
    pattern= re.compile('(?<!node)\d+.\d+')
    distance = pattern.findall(node)

结果是这样的

['0.04', '11.11', '4 72']

我想要的是这个

['0.04', '11.11', '72.21']

关于修正这个正则表达式有什么建议吗?

最佳答案

在正则表达式中,. 字符被解释为通配符并且可以匹配(几乎)任何字符。因此,您的搜索模式实际上允许一个数字或一组数字,后跟任何字符,然后是另一个数字或一组数字。要停止对点字符的这种解释,请使用反斜杠 \ 将其转义。

(旁白:您不需要在循环内编译正则表达式模式。事实上,这会减慢您的代码速度。)

pattern = re.compile('(?<!node)\d+\.\d+')
for node in nodes:
    distance = pattern.findall(node)
    print distance

输出:

['0.04', '11.11', '72.21']
['1247.25', '20.59', '64.94']

关于python - 如何在 python 中修复这个正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30537314/

相关文章:

python - 在针对官方 python :3 docker image? 的 Dockerfile 中使用的 python 脚本中使用的正确 shebang 是什么

regex - 使用正则表达式删除整个查询字符串

python - ord ('q' ) 和 0xFF 的用法

python - Scrapy 中的变量

python - 使用字典作为查找替换 pandas 数据框值

Python BitTorrent 库

Java 正则表达式匹配每 2 个字母之间带有可选多个注释的单词(如何反向引用正则表达式子表达式)

regex - 正则表达式:(?!…)是什么意思?

javascript - 验证 IPv4、IPv6 和主机名

php - 正则表达式白名单问题