Python 对多行使用正则表达式

Python 对多行使用正则表达式,python,regex,Python,Regex,使用正则表达式为以下行提取表达式的最佳方法是什么: Sigma 0.10 index = $5.00 beta .05=$25.00 .35 index (or $12.5) Gamma 0.07 在任何情况下,我都希望从每一行中提取数值(例如,第1行中的“0.10”)和(如果可用)美元金额或第1行中的“$5.00” import re s="""Sigma 0.10 index = $5.00 beta .05=$25.00 .35 index (or $12.5) Gamma 0.07""

使用正则表达式为以下行提取表达式的最佳方法是什么:

Sigma 0.10 index = $5.00
beta .05=$25.00
.35 index (or $12.5)
Gamma 0.07
在任何情况下,我都希望从每一行中提取数值(例如,第1行中的“0.10”)和(如果可用)美元金额或第1行中的“$5.00”

import re
s="""Sigma 0.10 index = $5.00
beta .05=$25.00
.35 index (or $12.5)
Gamma 0.07"""
print re.findall(r'[0-9$.]+', s)
输出:

['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
['0.10', '$5.00', '$25.00', '$12.5', '0.07']
['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
更严格的正则表达式:

print re.findall(r'[$]?\d+(?:\.\d+)?', s)
输出:

['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
['0.10', '$5.00', '$25.00', '$12.5', '0.07']
['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
如果您还想匹配
.05

print re.findall(r'[$]?(?:\d*\.\d+)|\d+', s)
输出:

['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']
['0.10', '$5.00', '$25.00', '$12.5', '0.07']
['0.10', '$5.00', '.05', '$25.00', '.35', '$12.5', '0.07']

基本正则表达式应该是:
\$?\d+(\.\d+)
,这将获得数字。不幸的是,我知道JavaScript/C中的正则表达式,所以不确定如何在python中执行多行操作。但是应该是一个非常简单的标志。

使用
re.MULTILINE
标志和
\n
来表示换行符

source = '''Sigma 0.10 index = $5.00
beta .05=$25.00
.35 index (or $12.5)
Gamma 0.07'''
import re

# only handles two top lines; extend to taste
rx = re.compile(
  'Sigma (\d*\.\d+) index = (\$\d*\.\d+)\nbeta (\d*\.\d+).*', 
   re.MULTILINE
)

print rx.search(source).groups()
# prints ('0.10', '$5.00', '.05')

还可以考虑在您的行中使用
.split('\n')
,并使用几个更简单的regexp,每个结果行一个。

您能解释一下为什么我需要在末尾使用
表示它可能在那里,也可能不在那里。例如,
spam?
将匹配“spam”或“spam”,因为
紧跟在“s”之后。但是,如果我们将它用于一个组(封装在
()
中的东西),那么它将应用于整个组。所以,
(\。\d+)?
表示匹配,如果有一个小数后跟一些数字。。。或者不是。在解析之前拆分输入对于正确性和可读性来说都是个坏主意。@siebz0r:拆分是对作为源格式一部分的换行符进行解析。对我来说似乎是合法的。