Python regex: Remove a pattern at the end of string

14,490

Solution 1

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

Solution 2

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.

Solution 3

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

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

Solution 4

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'
Share:
14,490

Related videos on Youtube

90abyss
Author by

90abyss

Updated on September 15, 2022

Comments

  • 90abyss
    90abyss over 1 year

    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)
    
  • rebeling
    rebeling over 8 years
    blah. blah. boom. What about '.'.join(s.split('.')[:-1])
  • idjaw
    idjaw over 8 years
    I don't see that it is necessary to convert your list to a string when you can simply just extract the string you need after your split right away.
  • rebeling
    rebeling over 8 years
    blah. blah. boom.(4/2) What do you expect to get?
  • idjaw
    idjaw over 8 years
    Apologies, I don't understand what you are asking.
  • rebeling
    rebeling over 8 years
    No worries. But sometimes there is another dot. Try print "blah. blah. boom.(4/2)".split('.')[0]
  • idjaw
    idjaw over 8 years
    Oh I understand now, thanks. The intention of this was more to fall with the pattern as exactly specified by the OP and the shortest solution path to that was to just split on the ..