user2709885
user2709885

Reputation: 423

How to use regular expression to detect parenthesis at the end of a string?

I am using if/elif statements in Python to match some strings, but I need help in matching one particular type of string. I want all strings that have parenthesis '()' in the end to match the same if condition. For example, string = "Tennis (5.5)" or string = "Football (6.3)".

def method(string):
    if (string has parenthesis in the end): 

Can I use some regular expression for this ? I am not sure how to go about it.

Upvotes: 0

Views: 59

Answers (2)

Roland Bischof
Roland Bischof

Reputation: 260

In the case you'd prefer regex, this is probably the simplest solution. It asserts, if there is a closing parenthesis at the end of line, irrespectively of trailing blanks:

"\)$"

For example:

test1 = "Tennis (5.5) "
test2 = "Football (6.3)"

res1 = bool(re.search(r"\)$", test1.strip()))
res2 = bool(re.search(r"\)$", test2.strip()))

print(res1, res2, sep='\n')

>>> True
>>> True

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

I think you mean this,

if re.search(r'(?m)\([^()]*\)$', line):

$ asserts that we are at the end of a line.

Upvotes: 2

Related Questions