Python正则表达式删除字符串

时间:2011-12-25 18:34:58

标签: python regex

我的文字中的记录以PHOTO开头,以\n结尾,如何使用正则表达式删除此文本。

3 个答案:

答案 0 :(得分:11)

我正在做几种方法。

切割字符串:

>>> string = "PHOTOThe text which should be present\n"
>>> string[5:-1]
'The text which should be present'

使用正则表达式:

>>> import re
>>> match = re.match("PHOTO(.+)\n", string)
>>> match.groups()
('The text which should be present',)

答案 1 :(得分:3)

我知道这不是正则表达式,但

怎么样
x = x[5:-1]

答案 2 :(得分:2)

你尝试过这样的事吗?

re.sub('^PHOTO.*\n', '', <your_string>)