【发布时间】:2018-03-20 23:20:40
【问题描述】:
我正在尝试使用正则表达式将所选文本替换为所选文本中的一个单词。我尝试了 re.sub() 但它似乎将第二个参数“我想用文本替换它的单词”作为字符串,而不是正则表达式。
这是我的字符串:
I go to Bridgebrook i go out <ERR targ=sometimes> some times </ERR> on Tuesday night i go to Youth <ERR targ=club> clob </ERR> .
这是我的代码:
# The regex of the form <ERR targ=...> .. </ERR>
select_text_regex = r"<ERR[^<]+<\/ERR>"
# The regex of the correct word that will replace the selected text of teh form <ERR targ=...> .. </ERR>
correct_word_regex = r"targ=([^>]+)>"
line = re.sub(select_text_regex, correct_word_regex, line.rstrip())
我明白了:
I go to Bridgebrook i go out targ=([^>]+)> on Tuesday night i go to
Youth targ=([^>]+)> .
我的目标是:
I go to Bridgebrook i go out sometimes on Tuesday night i go to
Youth club .
Python 是否支持使用 Regex 替换两个字符串?
【问题讨论】:
标签: python regex python-3.x