Jd_mahmud
Jd_mahmud

Reputation: 41

Finding substrings enclosed within first brackets

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']

Upvotes: 1

Views: 74

Answers (2)

Daweo
Daweo

Reputation: 36390

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.

Upvotes: 3

mozway
mozway

Reputation: 260455

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']

Upvotes: 3

Related Questions