Python: How to print a regex string?

I want to combine part of a string (specific word) and print it. Exactly what grep -o does. My word, for example, is "yellow dog," and it can be found in a line that spans several lines.

 [34343] | ****. "Example": <one>, yellow dog tstring0 123 tstring1 456 tstring2 789 

Try this regular expression mydog = re.compile(', .*\n') and then if mydog.search(string): print only matching words.

How do I get only a yellow dog out?

+8
python regex
source share
2 answers

Using capture group and findall:

 >>> import re >>> s = """[34343] | ****. "Example": <one>, yellow dog ... tstring0 123 ... tstring1 456 ... tstring2 789""" >>> mydog = re.compile(', (.*)\n') >>> mydog.findall(s) ['yellow dog'] 

If you need only the first match, then:

 >>> mydog.findall(s)[0] 'yellow dog' 

Note: you must handle IndexError if s does not contain a match.

+12
source share

If you do not specify a capture group, text that matches the entire expression will be contained with matchResult.group(0) . In your case it will be ', yellow dog\n' . If you just want a yellow dow , you must add a capture group to the expression:, , (.*?)\n yellow dow Please note that I also changed .* To .*? so that he is not greedy and stops when he finds the first line break.

 >>> s = '''[34343] | ****. "Example": <one>, yellow dog tstring0 123 tstring1 456 tstring2 789''' >>> mydog = re.compile(', (.*?)\n') >>> matchResult = mydog.search(s) >>> if matchResult: print(matchResult.group(1)) yellow dog 
+4
source share

All Articles