wrongusername
wrongusername

Reputation: 18918

How can I substitute a regex only once in Python?

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?

Upvotes: 4

Views: 6762

Answers (5)

Andrew Cheong
Andrew Cheong

Reputation: 30303

I think your phrasing, "first instance," caused everyone else to answer in the direction of count, but if you meant that you want to delete a phrase only if it fully matches a phrase you seek, then first you have to define what you mean by a "phrase", e.g. non-lower-case characters:

DON'T DELETE THIS

In which case, you can do something like this:

(?<![^a-z]+)\s+DELETE THIS\s+(?![^a-z]+)

I'm not sure whether Python allows arbitrary-length negative lookbehind assertions. If not, remove the first +.

Upvotes: 1

bukzor
bukzor

Reputation: 38532

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-'.

Upvotes: 3

Ervin
Ervin

Reputation: 746

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

Upvotes: 19

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

you can use str.replace() for this:

In [9]: strs="I want to DELETE THIS go to DON'T DELETE THIS the supermarket"

In [10]: strs.replace("DELETE THIS","",1) # here 1 is the count
Out[10]: "I want to  go to DON'T DELETE THIS the supermarket"

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85883

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer.

re.sub(pattern, repl, string, count=0, flags=0)

Set count = 1 to only replace the first instance.

Upvotes: 2

Related Questions