[英]Regex to match one or more digits
I got dataset like that (it's opened as str from file): 我得到了这样的数据集(从文件中以str形式打开):
MF8='out1mf8':'constant',[1944.37578865883]
MF9='out1mf9':'constant',[2147.79853787502]
MF10='out1mf10':'constant',[565.635908155949]
MF11='out1mf11':'constant',[0]
MF12='out1mf12':'constant',[0]
I need this values in brackets, so a created regex: 我需要将这些值放在方括号中,以便创建一个正则表达式:
outmfPattern = 'out\dmf\d'
and used: 并使用:
re.findall(outmfPattern, f)
It's working nice until mf = 9
. 直到mf = 9
很好。 Does anybody has idea how to handle with this? 有人知道如何处理吗?
Let's break down your regex out\\dmf\\d
: 让我们将您的正则表达式分解为out\\dmf\\d
:
out
matches the sequence 'out'
out
与序列'out'
匹配 \\d
matches a digit \\d
匹配一个数字 mf
match the sequence 'mf'
mf
匹配序列'mf'
\\d
matches a digit \\d
匹配一个数字 If you want to match something like out1mf11
, you'll need to look for 2 digits at the end. 如果你想匹配类似out1mf11
,你需要寻找在最后2位数字。
You can use out\\dmf\\d+
, or, if you want to match only 1 or 2 digits at the end, out\\dmf\\d{1,2}
. 您可以使用out\\dmf\\d+
,或者,如果您只希望末尾匹配1或2位数字,则可以使用out\\dmf\\d+
out\\dmf\\d{1,2}
。
In [373]: re.findall('out\dmf\d+', text)
Out[373]: ['out1mf8', 'out1mf9', 'out1mf10', 'out1mf11', 'out1mf12']
Furthermore, if you want to add brackets to those search items, you probably should look at re.sub
instead: 此外,如果要在这些搜索项中添加方括号,则可能应查看re.sub
而不是:
In [377]: re.sub('(out\dmf\d+)', r'(\1)', text)
Out[377]: "MF8='(out1mf8)':'constant',[1944.37578865883] MF9='(out1mf9)':'constant',[2147.79853787502] MF10='(out1mf10)':'constant',[565.635908155949] MF11='(out1mf11)':'constant',[0] MF12='(out1mf12)':'constant',[0]"
re.sub
replaces the captured groups with the same enclosed in parens. re.sub
将捕获的组替换为括号中包含的相同组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.