Python:正则表达式,但不包括字母数字

时间:2011-08-11 17:55:30

标签: python regex

是否有正则表达式可供查找,例如">ab",但结果中不包含">"

我想使用re.sub替换一些字符串,我希望找到以">"开头的字符串而不删除">"

3 个答案:

答案 0 :(得分:7)

你想要一个积极的外观断言。请参阅the docs

r'(?<=>)ab'

它需要是固定长度的表达式,它不能是可变数量的字符。基本上,做

r'(?<=stringiwanttobebeforethematch)stringiwanttomatch'

所以,一个例子:

import re

# replace 'ab' with 'e' if it has '>' before it

#here we've got '>ab' so we'll get '>ecd'
print re.sub(r'(?<=>)ab', 'e', '>abcd') 

#here we've got 'ab' but no '>' so we'll get 'abcd'
print re.sub(r'(?<=>)ab', 'e', 'abcd') 

答案 1 :(得分:6)

您可以在sub:

中使用反向引用
import re
test = """
>word
>word2
don't replace
"""
print re.sub('(>).*', r'\1replace!', test)

输出:

>replace!
>replace!
don't replace

我相信当你说“我想要使用re.sub替换某些字符串时,我会实现您真正想要的内容,并且我希望找到以”>“开头的字符串而不删除”{{1 }}”。“

答案 2 :(得分:0)

如果你想避免使用re模块,你也可以使用startswith()字符串方法。

>>> foo = [ '>12', '>54', '34' ]
>>> for line in foo:
...     if line.startswith('>'):
...             line = line.strip('>')
...     print line
... 
12
54
34
>>>