Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assistance needed for regex python

Tags:

python

regex

i have a file similar to that shown below- is it possible to perform a regex expression

text1  769,230,123
text2  70
text3  213,445
text4  24,356
text5  1,2,4

to give output as shown here?

['769','230','123']
['70']
['213','445']

My current code is as follows:

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

Any help or direction would be greatly useful to me. Thank you

like image 383
Script kiddies Avatar asked Aug 02 '26 00:08

Script kiddies


2 Answers

The following regex will extract the comma separated numbers from the line, and then we can apply split(',') in order to extract the numbers:

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

OUTPUT

769
230
123
like image 145
Nir Alfasi Avatar answered Aug 04 '26 13:08

Nir Alfasi


It looks like you could just findall number sequences:

regex = re.compile("[ ,]([0-9]+)")
like image 42
Andrew Johnson Avatar answered Aug 04 '26 14:08

Andrew Johnson