0

I have a text file, say text.txt and it has the following information

uncle sam
 work - xyz abc
uncle andrew
 work - xyz abc
aunt michelle 
 work - abcd wxy
aunt rosy 
 work - asdff   

problem: search for the word 'uncle' and then print its corresponding work using the regular expression of python.

output :

uncle sam
 work - xyz abc
uncle andrew
 work - xyz abc

I am new to python programming,so any help is appreciated. Thanks!

1 Answer 1

1

With this simple regex:

^uncle.*[\r\n]+.*

Use like this:

for match in re.finditer(r"(?m)^uncle.*[\r\n]+.*", subject):
    # matched text: match.group(0)

Token-by-Token explanation:

(?m)                     # ^ matches at the beginning of every line
^                        # the beginning of the string
uncle                    # 'uncle'
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))
[\r\n]+                  # any character of: '\r' (carriage return),
                         # '\n' (newline) (1 or more times (matching
                         # the most amount possible))
.*                       # any character except \n (0 or more times
                         # (matching the most amount possible))
1
  • Your code only prints the first match (uncle sam), as ^ will only match beginning of the string, add the flag re.MULTILINE to be able to match on every line. If you use normal string "" \r\n will be converted into newline or return characters, generally you want to use r"[\r\n]" (raw string) or you should escape \ -> "[\\r\\n]"
    – emil
    Jun 8, 2014 at 10:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.