xvienxz2
xvienxz2

Reputation: 63

Retrieve first word in parenthesis in Python

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

Answers (6)

Mahen Gandhi
Mahen Gandhi

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

Narendra Kamatham
Narendra Kamatham

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

blhsing
blhsing

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

Samuel Nde
Samuel Nde

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

U13-Forward
U13-Forward

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

KingRadical
KingRadical

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

Related Questions