Reputation: 63
I googled and read up on some codes here Regular expression to return text between parenthesis
but say for example I have the following string
"[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
How would I output "STR" only and not (Warriors -> Berserker) ?
Thanks!
Upvotes: 2
Views: 1684
Reputation: 351
Consider the following string,
s = 'I am John (John (M) Doe)'
The first word within valid parentheses should be 'John (M) Doe' and not 'John (M'. The following code would keep count of the open and closed parentheses:
opn = 0
close = 0
new_str = ''
add = False
for i in s:
if not add:
if i == '(':
opn += 1
add = True
else:
if i == '(':
new_str += i
opn += 1
elif i == ')':
close += 1
if opn == close:
break
else:
new_str += i
else:
new_str += I
print(new_str)
This yields:
John (M) Doe
Hope this helps!
Upvotes: 1
Reputation: 340
import re
str1 = "[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
m = re.findall(r'(\(\w+\))',str1)
print m
Result:['(STR)']
Here the string we need to find in given text is located between ( ) with no spaces and special charecters,So ( \w+ ) means more than one charecters present in ( )
Upvotes: 0
Reputation: 106465
You can slice the string with indices returned by str.find
:
s = "[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
s[s.find('(')+1:s.find(')')]
which returns: STR
Upvotes: 0
Reputation: 2743
Use re.search
with group as explained by @KingRadical or use re.findall
and then select the first element.
s = "[Guide] Strength (STR are long) is recommended on Warriors (Warriors -> Berserker)"
re.findall('\(([^\)]+)\)', s) # returns all matches
>>> ['STR are long', 'Warriors -> Berserker']
re.findall('\(([^\)]+)\)', s)[0] # returns the first match which is what you want.
>>> 'STR are long'
Note:
If there is no match in the string s, re.findall
will return an empty list while re.search
will return a None
object.
Upvotes: 0
Reputation: 71570
Or re.split
:
>>> import re
>>> s="[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
>>> result = re.split(r"\s+(?=[^()]*(?:\(|$))", s)
>>> next((i[1:-1] for i in result if i[0]=='(' and i[-1]==')'),'No sub-strings that are surrounded by parenthesis')
'STR'
>>>
Note: here if the strings does not contain any sub-string surrounded by parenthesis, it will Output 'No sub-strings that are surrounded by parenthesis'
, if that's not needed you can just do:
>>> next((i[1:-1] for i in result if i[0]=='(' and i[-1]==')'))
Or:
>>> [i[1:-1] for i in result if i[0]=='(' and i[-1]==')'][0]
Upvotes: 0
Reputation: 1312
>>> import re
>>> s = "[Guide] Strength (STR) is recommended on Warriors (Warriors -> Berserker)"
>>> re.search(r'\(([^)]+)\)', s).group(1)
<<< 'STR'
re.search
returns the first match
.group(1)
returns the contents of the first capture group, which is ([^)]+)
Upvotes: 1