正则表达式在多个字符串的末尾查找数字
Regex find digits at the end of multiple strings
下面是我的字符串,它来自标准输出。
我正在寻找一种方法来查找传感器的所有十进制数。我想提供我的正则表达式模式“TP1”,并希望我的 return 看起来像这样:
[156.2 , 30]
我正在使用 re.findall()
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
我可以找到字符串的结尾,但不能通过输入找到:请看这里:https://regex101.com/r/IyqtsL/1
这是我正在尝试的代码
\d+\.\d+?$
通过标志启用多行模式:在 regex101.com 上,该选项在模式输入字段的右侧可用(默认情况下您可以看到 /g
)。在 Python,可以将flags作为第三个参数传给re.findall()
:
import re
sensor = "TP1"
text = """
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
"""
re.findall(fr'^{sensor}\s+\w+\s+([\d\.]+)$', text, re.MULTILINE)
# returns ['156.2', '30]
所有标志都在 documentation 中描述。
您也可以直接拆分文本。
鉴于:
txt = """\
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
"""
你可以这样做:
>>> [sl[-1] for sl in (line.split() for line in txt.splitlines()) if sl[0]=='TP1']
['156.2', '30']
下面是我的字符串,它来自标准输出。
我正在寻找一种方法来查找传感器的所有十进制数。我想提供我的正则表达式模式“TP1”,并希望我的 return 看起来像这样:
[156.2 , 30]
我正在使用 re.findall()
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
我可以找到字符串的结尾,但不能通过输入找到:请看这里:https://regex101.com/r/IyqtsL/1
这是我正在尝试的代码
\d+\.\d+?$
通过标志启用多行模式:在 regex101.com 上,该选项在模式输入字段的右侧可用(默认情况下您可以看到 /g
)。在 Python,可以将flags作为第三个参数传给re.findall()
:
import re
sensor = "TP1"
text = """
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
"""
re.findall(fr'^{sensor}\s+\w+\s+([\d\.]+)$', text, re.MULTILINE)
# returns ['156.2', '30]
所有标志都在 documentation 中描述。
您也可以直接拆分文本。
鉴于:
txt = """\
TP1 BCArc 156.2
TP2 Max: of output here 0.01
TP3 some:other example 1 here 30.70
TP1 BCArc 30
TP2 Max: of output here 2.22
"""
你可以这样做:
>>> [sl[-1] for sl in (line.split() for line in txt.splitlines()) if sl[0]=='TP1']
['156.2', '30']