python re.sub 中的正则表达式条件 - 怎么样?
python regex conditional in re.sub - how?
是否可以在 re.sub()
中使用 python 的正则表达式条件?我尝试了很多变体,但都没有成功。这是我的。
import re
# match anything: <test> always true
a = re.compile('(?P<test>.*)')
# return _'yes'_ or 'no' based on <test>
a.sub('(?(\g<test>)yes|no)', 'word')
'(?(word)yes|no)'
我预计 'yes' 或 'no,' 不是实际测试。
我从中得到的是看到 <test>
但正则表达式条件未被执行。还有其他方法可以实现吗?
我试过 re.sub(pat, rep, str)
结果相同。
如果要执行条件替换,请使用 函数
作为 替换 参数。
这个函数接受一个match参数(已经抓到了什么)
其结果是要替换的文本。
在替换函数中引用名为 test 的捕获组,
使用 group('test')
.
示例程序:
import re
def replTxt(match):
return 'yes' if match.group('test') else 'no'
a = re.compile('(?P<test>.+)')
result = a.sub(replTxt, 'word')
print(result)
但是我有这样一句话:
no
永远不会被该程序取代。
如果正则表达式不匹配,replTxt
函数将不会被调用。
有可能 test 组什么都不匹配,但有一些
已匹配:
- 这个捕获组应该是有条件的(
?
在它之后),
- 为了不匹配空文本,正则表达式应该包含
更多匹配的东西,例如
(?P<test>[a-z]+)?\d
.
是否可以在 re.sub()
中使用 python 的正则表达式条件?我尝试了很多变体,但都没有成功。这是我的。
import re
# match anything: <test> always true
a = re.compile('(?P<test>.*)')
# return _'yes'_ or 'no' based on <test>
a.sub('(?(\g<test>)yes|no)', 'word')
'(?(word)yes|no)'
我预计 'yes' 或 'no,' 不是实际测试。
我从中得到的是看到 <test>
但正则表达式条件未被执行。还有其他方法可以实现吗?
我试过 re.sub(pat, rep, str)
结果相同。
如果要执行条件替换,请使用 函数 作为 替换 参数。
这个函数接受一个match参数(已经抓到了什么) 其结果是要替换的文本。
在替换函数中引用名为 test 的捕获组,
使用 group('test')
.
示例程序:
import re
def replTxt(match):
return 'yes' if match.group('test') else 'no'
a = re.compile('(?P<test>.+)')
result = a.sub(replTxt, 'word')
print(result)
但是我有这样一句话:
no
永远不会被该程序取代。
如果正则表达式不匹配,replTxt
函数将不会被调用。
有可能 test 组什么都不匹配,但有一些 已匹配:
- 这个捕获组应该是有条件的(
?
在它之后), - 为了不匹配空文本,正则表达式应该包含
更多匹配的东西,例如
(?P<test>[a-z]+)?\d
.