正则表达式:匹配重复(任意时间)模式,但按单独的组排序

时间:2018-11-12 09:13:06

标签: python regex regex-group

我试图匹配(如果可能的话,仅)行中包含的坐标值:

function f is described by the (x,y) couples: 0.000000E+00 0.000000E+00  5.00000     0.500000E-01  1.0000     0.290000      2.0000      1.56000      3.0000      5.47000      4.0000      17.3000      4.50000      31.2000      5.0000      52.6000

第一对符合要求,也就是说,分为两个不同的组,

(?<=\bcouples:\s)(\S+)\s+(\S+)\s+

然后

    (?<=\bcouples:\s)((\S+)\s+(\S+)\s+)+

匹配整行,但仅将最后两个坐标分成不同的组。

精度:坐标对的数量未知,因此只需加几次

(\S+)\s+(\S+)\s+
正则表达式末尾的

是不可行的。

感谢您的输入!

1 个答案:

答案 0 :(得分:1)

使用findall():

re.findall(r"(?:\s+([\d\.Ee+-]+)\s+([\d\.Ee+-]+))+?",s)

([\d\.Ee+-]+)\s+([\d\.Ee+-]+) --> two float numbers,
                                  () each of grouped;
 (?:\s+ ... )+? -->  +? there can be more couples, ? means non-greedy matching,
                     (?: the outer group is not interesting;

编辑: 您可以选择适当的行:

 if "couples:" in s:
     coords= re.findall(...)

如果您的文本包含更多“对”,则可以拆分它。在以下示例中,我们可以将正则表达式应用于分割后的字符串的第二部分或第三部分,或两部分都使用:

s="function f is described by the (x,y) couples: 0.000000E+00 0.000000E+00  5.00000     0.500000E-01 function g is described by the (x,y) couples: 0.1E+00 0.2E+00  9.00000     0.900000E-01"

ls=s.split("couples")
print(ls)
['function f is described by the (x,y) ',
 ': 0.000000E+00 0.000000E+00  5.00000     0.500000E-01 function g is described by the (x,y) ',
 ': 0.1E+00 0.2E+00  9.00000     0.900000E-01']

 re.findall(r"(?:\s+([\d\.Ee+-]+)\s+([\d\.Ee+-]+))+?",ls[1])
 [('0.000000E+00', '0.000000E+00'), ('5.00000', '0.500000E-01')]
相关问题