Python正则表达式不匹配 [英] Python regular expression not matching

查看:102
本文介绍了Python正则表达式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是其中之一,我确定我遗漏了一些简单的东西,但是......在下面的示例程序中,我正在尝试使用 Python 的 RE 库来解析字符串line"以获取百分号前的浮点数,即90.31".但是代码总是打印不匹配".

This is one of those things where I'm sure I'm missing something simple, but... In the sample program below, I'm trying to use Python's RE library to parse the string "line" to get the floating-point number just before the percent sign, i.e. "90.31". But the code always prints "no match".

我也尝试了其他几个正则表达式,结果都一样.我错过了什么?

I've tried a couple other regular expressions as well, all with the same result. What am I missing?

#!/usr/bin/python
import re
line = '    0 repaired, 90.31% done'
pct_re = re.compile(' (\d+\.\d+)% done$')
#pct_re = re.compile(', (.+)% done$')
#pct_re = re.compile(' (\d+.*)% done$')
match = pct_re.match(line)
if match: print 'got match, pct=' + match.group(1)
else: print 'no match'

推荐答案

match 只匹配开头的字符串.如果您改为执行 pct_re.search(line),您的代码可以正常工作.

match only matches from the beginning of the string. Your code works fine if you do pct_re.search(line) instead.

这篇关于Python正则表达式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆