如何查找特定行中的所有匹配子字符串?

时间:2018-06-05 14:46:46

标签: python regex

我有几行文字列出了处理器的几个指令。我需要查找<x; y, z>形式的所有模式。每行中可能有两个或更多这样的模式。我希望将每个集合中的所有模式(&lt;&gt;内的三个数字)复制到一个列表中以供进一步分析。

我尝试过使用entries = re.findall("<[0-9]; [0-9], [0-9]>", line)

我希望每行的输出看起来像这样:

输出

[x, y, z, a, b, c] # (where all the entries are integer values)

然而,这还不够,实现我想要的最佳方式是什么?

3 个答案:

答案 0 :(得分:0)

Say line就像是 [x for x in re.split(r'[<;,>]',line) if re.search('[0-9]',x) or re.search('[a-z]',x)]

Out[347]: ['7', '8', '9', '8', '7', '4', '7', 'a', 'z'] a.Zip(a.Skip(1), (x, y) => Enumerable.Repeat(x, 1).Concat(Enumerable.Repeat(y, 1))) .Zip(a.Skip(2), (xy, z) => xy.Concat(Enumerable.Repeat(z, 1))) .Where((x, i) => i % 3 == 0)

答案 1 :(得分:0)

这有点笨拙,但它应该能满足你的需要。

out

基本上,在使用findall找到所需的所有项目后,我们使用split和strip将数字分开,并将它们同时转换为整数。 strip()应该是列表列表,其中每个项目将按顺序包含数字。

请注意,我使用了您在代码中看到的间距。如果没有空格,则{{1}}命令是不必要的。

答案 2 :(得分:0)

import re

text  = ["<92; 29,17><99; 8,3>","no match here","<2; 9,1><999;18,3>"]

lines = []    # all the line results 

for line in text:  # go over each line

    oneLine = []       # matches for one line 

    for m in re.findall("<(\d+); ?(\d+),(\d+)>", line):  # find all patterns
        oneLine.extend(map(int,m))                       # convert to int, extend oneLine

    if oneLine:                                          # add to lines if not empty
        lines.append(oneLine) 

print (lines)

输出:

[[92, 29, 17, 99, 8, 3], [2, 9, 1, 999, 18, 3]] # each inner list is 1 line

我修改了模式,它寻找

<     - literal character
\d+   - 1 to n numbers
;     - literal character
space - optional space
\d+   - 1 to n numbers
,     - literal ,
\d+   - 1 to n numbers
>     - literal > 
相关问题