how to print the next word of a sprecific string in a line using python?

Viewed 70

I am trying to print the text in the ""

s="I love playing "badminton", it is a great sport."
s1 = re.search('playing (\w+)', s).groups()[0]
print (s1)

The above code perfectly working if the input is "I love playing badminton, it is a great sport." in this format. I am trying to print the text whatever in "". I am sure this is pretty simple, Because of the initial stage in learning python don't know where exactly I am going. Any help would be appreciated. Thank you

2 Answers

Try escaping (\) the quotes in your string s, that way python sees them as part of the string. Then to optionally match them in your regex you can use ?.

import re

s = "I love playing \"badminton\", it is a great sport."
s1 = re.search('playing "?(\w+)"?', s).groups()[0]
print(s1)

# prints
badminton

If you want to print playing badminton, you can use 2 capturing groups and put the double quotes outside of the group.

Instead of indexing in .groups()[0], you can also use .group(1)

\b(\w+ )"(\w+)"

Regex demo

Example code

import re

s = """I love playing "badminton", it is a great sport."""
s1 = re.search(r'\b(\w+ )"(\w+)"', s)
if s1:
    print (s1.group(1) + s1.group(2))

Output

playing badminton

Or you might match all non word characters in between until the next word if the double quotes can be other non word chars or not present.

\b(playing )\W*(\w+)

Regex demo

Related