如何在python中匹配这个正则表达式?

时间:2012-03-26 04:17:49

标签: python regex

我有以下字符串s =“~VERSION 11 11 11.1 222 22 22.222”

我想将以下内容提取到以下变量中:

string Variable1 = "11 11 11.1"
string Variable2 = "222 22 22.222"

如何使用正则表达式提取此内容?或者有更好的替代方式吗? (注意,我想要提取的标记之间可能存在可变间距,而主要字符可能不是〜,但它绝对是一个符号:

e.g。可能是:

~   VERSION   11 11 11.1  222 22 22.222
$   VERSION 11 11 11.1      222 22 22.222
@      VERSION    11 11 11.1          222 22 22.222

如果正则表达式没有意义,或者有更好的方法,请推荐。 如何在python中将提取预先形成为这两个变量?

4 个答案:

答案 0 :(得分:2)

试试这个:

import re

test_lines = """
~   VERSION   11 11 11.1  222 22 22.222
$   VERSION 11 11 11.1      222 22 22.222
@      VERSION    11 11 11.1          222 22 22.222
"""

version_pattern = re.compile(r"""
[~!@#$%^&*()]               # Starting symbol
\s+                         # Some amount of whitespace
VERSION                     # the specific word "VERSION"
\s+                         # Some amount of whitespace
(\d+\s+\d+\s+\d+\.\d+)      # First capture group
\s+                         # Some amount of whitespace
(\d+\s+\d+\s+\d+\.\d+)      # Second capture group
""", re.VERBOSE)

lines = test_lines.split('\n')

for line in lines:
    m = re.match(version_pattern, line)
    if (m):
        print (line)
        print (m.groups())

给出输出:

~   VERSION   11 11 11.1  222 22 22.222
('11 11 11.1', '222 22 22.222')
$   VERSION 11 11 11.1      222 22 22.222
('11 11 11.1', '222 22 22.222')
@      VERSION    11 11 11.1          222 22 22.222
('11 11 11.1', '222 22 22.222')

请注意使用带注释的详细正则表达式。

要将提取的版本号转换为数字表示(即int,float),请使用@Preet Kukreti答案中的正则表达式,并按照建议使用int()float()进行转换。

答案 1 :(得分:1)

您可以使用String的split方法。

v1 = "~ VERSION 11 11 11.1 222 22 22.222"
res_arr = v1.split(' ') # get ['~', 'VERSION', '11', '11', '11.1', '222', '22', '22.222']

然后根据需要使用元素2-4和5-7。

答案 2 :(得分:0)

import re
pattern_string = r"(\d+)\s+(\d+)\s+([\d\.]+)" #is the regex you are probably after
m = re.match(pattern_string, "222 22 22.222")
groups = None
if m:
    groups = m.groups()
    # groups is ('222', '22', '22.222')

之后,如果需要,您可以使用int()float()转换为原始数字类型。对于高性能代码,您可能希望事先使用re.compile(...)预编译正则表达式,并在生成的预编译正则表达式对象上调用match(...)search(...)

答案 3 :(得分:0)

正则表达式绝对容易。这将是一种方法

>>> st="~ VERSION 11 11 11.1 222 22 22.222 333 33 33.3333"
>>> re.findall(r"(\d+[ ]+\d+[ ]+\d+\.\d+)",st)
['11 11 11.1', '222 22 22.222', '333 33 33.3333']

在列表中获得结果后,您可以索引并获取单个字符串。