1

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!

1
  • it printed all the lines But you only have print(line) once, shouldn't it only be printing the last line? Commented Oct 4, 2018 at 3:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.