I have a string which is as following:
" I wanted my friends (he), (she), (they) around"
I want to get a list which will have ["he", "she", "they"].
Following is my code:
copy = " (he), (she), (they)"
x = re.findall(r'^{.}$', copy)
but this gives me an empty list as output.
I also tried the following:
import re
copy = '{he},{she}, {they}'
x = re.findall(r'\{([^]]*)\}', copy)
print(x)
But in this case, the output is:
['he},{she}, {they']
CodePudding user response:
You could use \((\w )\) (any succession of word characters surrounded by parentheses):
import re
re.findall('\((\w )\)', your_string)
input: your_string = " I wanted my friends (he), (she), (they) around"
output: ['he', 'she', 'they']
CodePudding user response:
Firstly you have round bracket ( ) in your example not curly bracket { } secondly ^ denotes start of line or string (depending on mode) whilst your bracketed expressions are inside, thirdly $ denotes end of line or string (depending on mode) whilst your bracketed expressions are inside. You should do
import re
text = " I wanted my friends (he), (she), (they) around"
print(re.findall(r'\((. ?)\)',text))
output
['he', 'she', 'they']
Note that I used so-called raw-string to avoid need of excessive escaping (see re module docs for further discussion) and need to use \( and \) to denote literal ( and literal ) as otherwise ( and ) denote group, which is also used in above pattern. . ? means match non-greedily one or more of any characters, ? is important to avoid single match he), (she), (they.
CodePudding user response:
Try this: try it online
>>> copy = " I wanted my friends (he), (she), (they) around"
>>> re.findall(r'\((.*?)\)', copy)
['he', 'she', 'they']
