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

标签 python regex

是否有一个正则表达式来查找,例如 ">ab" 但不在结果中包含 ">"

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

最佳答案

您需要一个积极的回顾断言。参见 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') 

关于Python:查找但不包含字母数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030584/

相关文章:

Python:生成不在列表中的随机整数

Java : how to get text between "http://" and first following "/" occurence ? 在第一次 "/"出现之后?

regex - Bash 脚本不会匹配正则表达式

mysql - 提取在正则表达式中匹配并以空格为界的子字符串

来自 postgresql 数据库的 Python 格式日期字符串

python - mvpa2 : restore SOM from Kohonen layer

python - pip 未使用 pip.conf 中定义的额外索引 url

javascript - 匹配类中特定结尾之前的任何字符

javascript - 使用正则表达式更新字符串

python : How to remove widget in kivy