简体   繁体   中英

Python regex: Get regex pattern in a text file and store in an array or list

I have this sample data inside a text file:

09-02||||||||09-14|07:24|12:15|12:58| | |

09-03| | | | | | |09-15|||||||

I'am trying to get all the data with this kind of pattern and store it in an array or list:

\d{2,3}-\d{2,3}

the output data when printed should be like this:

['09-02','09-14','09-02','09-15']

I tried this code but it printed all the lines matching the pattern:

n_date = re.compile('\d{2,3}-\d{2,3}')
with open('sample_2.txt', 'r') as n:
    for line in n:
        re.match(n_date, line)
print(line)

Please give me an idea on how can I just get the data matching my regex pattern not the whole line. Thank you!

Try this:

import re
n_date = re.compile('\d{2,3}-\d{2,3}')
with open('sample_2.txt', 'r') as n:
    n = n.read()
    result = re.findall(n_date, n)
    print(result)

It prints out:

['09-02', '09-14', '09-03', '09-15']

Your code just prints the last line of the for loop and you're not storing or using the result of re.match . re.findall will give you what you need, a list of all the elements matching the pattern.

You should use re.findall

n_date = re.compile('\d{2,3}-\d{2,3}')
result = []
with open(‘re.txt’, ‘r’) as n:
    for line in n:
         result += re.findall(n_date, line)
print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM