S
S
Sergey Nekrasov2016-02-12 16:51:36
Python
Sergey Nekrasov, 2016-02-12 16:51:36

How to compose a python regular expression?

there is a line like this:
''first:
numbers separated by commas
second:
numbers separated by commas"
I just can't figure out how to write a regular expression to collect separately all the numbers first and second in 2 different lists.
first=re.findall('\d+', data)
collects all the numbers.
If so:
first=re.findall('(\d+)\n\nsecond', data)
then puts to the first variable only the last number from first in the general data list.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2016-02-12
@chevylevel

First you need to find the necessary lines, and then parse them.

The code
>>> import re
>>> 
>>> text = """
... abc
... first:
... 10, 20, 30, 40, 50
... 
... def
... second:
... 600, 700, 800, 900, 1000
... 
... ghi
... """
>>> 
>>> list(map(re.compile(r'\d+').findall,
...          re.findall(r'(?:\d+(?:, )?)+', text)))

>>>

V
Vladimir Olohtonov, 2016-02-12
@sgjurano

next_line_is_first, next_line_is_second = False, False
first, second = [], []

for line in file:
    if next_line_is_first:
        first = line.split(,)
        next_line_is_first = False

    if next_line_is_second:
        second = line.split(,)
        next_line_is_second = False

    if 'first:' in line:
        next_line_is_first = True

    if 'second:' in line:
        next_line_is_second = True

print first, second

In general, it makes sense to be aware of when to use regular expressions. It's not always justified.
Put yourself in the place of a person who will be forced to delve into your code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question