90abyss
90abyss

Reputation: 7357

Python regex: Remove a pattern at the end of string

Input: blah.(2/2)

Desired Output: blah

Input can be "blah.(n/n)" where n can be any single digit number.

How do I use regex to achieve "blah"? This is the regex I currently have which doesn't work:

m = re.sub('[.[0-9] /\ [0-9]]{6}$', '', m)

Upvotes: 7

Views: 19661

Answers (4)

dawg
dawg

Reputation: 104102

Just match what you do not want and remove it. In this case, non letters at the end of the string:

>>> re.sub(r'[^a-zA-Z]+$', '', "blah.(1/2)")
'blah'

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115282

You need to use regex \.\(\d/\d\)$

>>> import re
>>> str = "blah.(2/2)"
>>> re.sub(r'\.\(\d/\d\)$', '',str)
'blah'

Regex explanation here

Regular expression visualization

Upvotes: 10

alecxe
alecxe

Reputation: 474241

I really like the simplicity of the @idjaw's approach. If you were to solve it with regular expressions:

In [1]: import re

In [2]: s = "blah.(2/2)"

In [3]: re.sub(r"\.\(\d/\d\)$", "", s)
Out[3]: 'blah'

Here, \.\(\d/\d\)$ would match a single dot followed by an opening parenthesis, followed by a single digit, followed by a slash, followed by a single digit, followed by a closing parenthesis at the end of a string.

Upvotes: 3

idjaw
idjaw

Reputation: 26600

Just do this since you will always be looking to split around the .

s = "stuff.(asdfasdfasdf)"
m = s.split('.')[0]

Upvotes: 3

Related Questions