Python 如何在特定行中找到所有匹配的子字符串?
我有几行文字列出了处理器的几条指令。我需要查找表单的所有模式Python 如何在特定行中找到所有匹配的子字符串?,python,regex,Python,Regex,我有几行文字列出了处理器的几条指令。我需要查找表单的所有模式。每行中可能有两个或更多这样的模式。我希望每个集合中的所有模式(其中的三位数字)都复制到一个列表中,以便进一步分析 我尝试过使用entries=re.findall(“,line) 我希望每行的输出如下所示: 输出 [x, y, z, a, b, c] # (where all the entries are integer values) 但是,这还不够,实现我想要的东西的最佳方法是什么?说行是这样的 line='' [x表示重新拆
。每行中可能有两个或更多这样的模式。我希望每个集合中的所有模式(其中的三位数字)都复制到一个列表中,以便进一步分析
我尝试过使用entries=re.findall(“,line)
我希望每行的输出如下所示:
输出
[x, y, z, a, b, c] # (where all the entries are integer values)
但是,这还不够,实现我想要的东西的最佳方法是什么?说行是这样的line=''
[x表示重新拆分中的x(r'[],行),如果重新搜索('[0-9]',x)或重新搜索('[a-z]',x)]
Out[347]:['7','8','9','8','7','4','7','a','z']
这有点笨拙,但它应该能满足你的需要
items = re.findall("<[0-9]+; [0-9]+, [0-9]+>", line)
out = []
for item in items:
separated = item.split(';')
out.append([int(separated[0].strip()), int(separated.split(',')[0].strip()), int(separated.split(',')[1].strip())])
items=re.findall(“,第行)
out=[]
对于项目中的项目:
separated=item.split(“;”)
out.append([int(分隔的[0].strip())、int(分隔的.split(','))[0].strip()、int(分隔的.split(','))[1].strip())
基本上,在使用findall找到所有需要的项之后,我们将使用split和strip将数字分离出来,同时将它们转换为整数<代码>输出应该是一个列表列表,其中每个项目将按顺序包含数字
注意,我在代码中使用了空格。如果没有空格,则不需要strip()
命令
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)
我修改了图案,它看起来像
< - literal character
\d+ - 1 to n numbers
; - literal character
space - optional space
\d+ - 1 to n numbers
, - literal ,
\d+ - 1 to n numbers
> - literal >
<-文字字符
\d+-1到n个数字
; - 一种为文学作品角色
空格-可选空格
\d+-1到n个数字
,-文字,
\d+-1到n个数字
>-文字>
请提供输入和预期输出的示例。现在还不清楚3位数字如何变成6位,我想你可能需要做一个re.findall,以及一些split和trim命令,除非你想做多个regex命令,然后转换成整数。
< - literal character
\d+ - 1 to n numbers
; - literal character
space - optional space
\d+ - 1 to n numbers
, - literal ,
\d+ - 1 to n numbers
> - literal >