regex-python需要帮助

regex-python需要帮助,python,regex,Python,Regex,我有一个类似于下面所示的文件-可以执行正则表达式吗 text1 769,230,123 text2 70 text3 213,445 text4 24,356 text5 1,2,4 如图所示给出输出 ['769','230','123'] ['70'] ['213','445'] 我目前的代码如下: with open(filename,'r') as output: for line in output: a = line a = a.s

我有一个类似于下面所示的文件-可以执行正则表达式吗

text1  769,230,123
text2  70
text3  213,445
text4  24,356
text5  1,2,4
如图所示给出输出

['769','230','123']
['70']
['213','445']
我目前的代码如下:

with open(filename,'r') as output:
    for line in output:
        a = line
        a = a.strip()
        #regex.compile here
        print regex.findall(a)

任何帮助或指导对我都会非常有用。谢谢

看起来您可以找到所有数字序列:

regex = re.compile("[ ,]([0-9]+)")

这不需要正则表达式。只需
line.split(',')
以下正则表达式将从行中提取逗号分隔的数字,然后我们可以应用
split(',')
来提取数字:

import re
line = "text1  769,230,123"
mat = re.match(r'.*? ([\d+,]+).*', line)
nums = mat.group(1).split(',')
for num in nums:
    print num
输出

769
230
123

以下内容应该适合您

>>> import re
>>> regex = re.compile(r'\b\d+\b')
>>> with open(filename, 'r') as output:
...     for line in output:
...         matches = regex.findall(line)
...         for m in matches:
...             print m
输出

769
230
123
70
213
445
24
356
1
2
4

假设在
文本35;
和逗号分隔值之间始终有2个空格。下面是一种将分离的值提取到数组中的简单方法

list = []
with open(filename,'r') as output:
    for line in output:
        line = line.strip('  ')
        list.append(line[1].strip(','))
这将生成一个嵌套列表

print list[0] #['769','230','123']
print list[1] #['70']
print list[2] #['213','445']

-1如果我们接受您的建议,第一行将返回“text1 769”作为拆分的第一个值。@alfasin可以拆分两次吗<代码>x.split(','),用于行中的x.split(“”)。我发现这更容易理解。@VivekRai依靠空格的数量和结果列表中拆分的每个元素的位置来计算似乎非常不安全。就在最后,OP希望尝试其他替代方案。谢谢-1使用此正则表达式搜索该行还将从
text1