Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I substitute a regex only once in Python?

Tags:

python

regex

So right now, re.sub does this:

>>> re.sub("DELETE THIS", "", "I want to DELETE THIS472 go to DON'T DELETE THIS847 the supermarket")
"I want to  go to DON'T  the supermarket"

I want it to instead delete only the first instance of "DELETE THISXXX," where XXX is a number, so that the result is

"I want to  go to DON'T DELETE THIS847 the supermarket"

The XXX is a number that varies, and so I actually do need a regex. How can I accomplish this?

like image 649
wrongusername Avatar asked Nov 29 '22 14:11

wrongusername


2 Answers

As written in the documentation for re.sub(pattern, repl, string, count=0, flags=0) you can specify the count argument in:

    re.sub(pattern, repl, string[, count, flags])

if you only give a count of 1 it will only replace the first

like image 130
Ervin Avatar answered Dec 06 '22 09:12

Ervin


From http://docs.python.org/library/re#re.sub:

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.

like image 20
bukzor Avatar answered Dec 06 '22 08:12

bukzor