Python:正则表达式查找但不包含字母数字字符

2 投票
3 回答
1649 浏览
提问于 2025-04-16 23:24

有没有一种正则表达式可以找到,比如说 ">ab",但结果中不包括 ">" 呢?

我想用 re.sub 来替换一些字符串,我想找到以 ">" 开头的字符串,但又不想把 ">" 去掉。

3 个回答

0

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

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

你想要使用一种叫做“正向回顾断言”的东西。可以查看这个文档了解更多。

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') 
6

你可以在sub中使用反向引用:

import re
test = """
>word
>word2
don't replace
"""
print re.sub('(>).*', r'\1replace!', test)

输出结果:

>replace!
>replace!
don't replace

我认为这能实现你真正想要的效果,当你说“我想用 re.sub 替换一些字符串,并且我想找到以 '>' 开头的字符串,但不想去掉 '>'。”

撰写回答