如何在Python中只替换一次regex?

2024-10-01 13:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以现在,re.sub会这样做:

>>> 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"

我希望它只删除“delete THISXXX”的第一个实例,其中XXX是一个数字,因此结果是

^{pr2}$

XXX是一个变化的数字,所以我确实需要一个正则表达式。我怎样才能做到这一点?在


Tags: thetorego数字thisdeletexxx
3条回答

可选参数count是要替换的模式出现的最大数量;count必须是非负整数。在

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

将count=1设置为仅替换第一个实例。在

正如在re.sub(pattern, repl, string, count=0, flags=0)documentation中所写的那样,您可以在中指定count参数:

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

如果你只给出1的计数,它只会替换第一个

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

相关问题 更多 >