24

我不熟悉正则表达式,如果有人使用正则表达式提供解决方案可以解释他们的语法,这样我就可以将它应用于未来的情况,那就太好了。

我有一个字符串(即。'Description: Mary had a little lamb'),我想删除'Description: '这样的字符串,'Mary had a little lamb,'但只读取第一个实例,这样如果字符串是'Description: Description',新字符串将是'Description.'

有任何想法吗?谢谢!

4

4 回答 4

56

Python 的str.replace有一个最大替换参数。因此,在您的情况下,请执行以下操作:

>>>mystring = "Description: Mary had a little lamb Description: "
>>>print mystring.replace("Description: ","",1)

"Mary had a little lamb Description: "

使用正则表达式基本上是一样的。首先,获取您的正则表达式:

"Description: "

由于 Python 对正则表达式非常好,因此在这种情况下,它只是您要删除的字符串。有了它,你想在 re.sub 中使用它,它也有一个 count 变量:

>>>import re
>>>re.sub("Description: ","",mystring,count=1)
'Mary had a little lamb Description: '
于 2012-05-18T07:35:52.737 回答
1

此正则表达式适用于任何“单词”,而不仅仅是“描述:”

>>> import re
>>> s = 'Blah: words words more words'
>>> print re.sub(r'^\S*\s', '', s)
words words more words
>>> 
于 2012-05-18T08:21:10.890 回答
0

使用regex仅指定计数参数,如1. re.sub尽管在这种情况下似乎regex不需要。

>>> import re
>>> text = 'Description: Mary had a little lamb'
>>> re.sub('Description: ','',text,1)
'Mary had a little lamb'
于 2012-05-18T07:34:54.927 回答
0

您可以不使用正则表达式,通过将countarg 设置为 1 来使用替换功能:

>>> string = 'Description: Mary had a little lamb Description'
>>> string.replace('Description', '', 1)
'Mary had a little lamb Description'
于 2019-12-25T13:35:14.850 回答