在Python中使用regex替换字符串

2024-04-29 09:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用正则表达式将所选文本中的单个单词替换为所选文本。我试过了回复sub()但它似乎将第二个参数“我要用文本替换的单词”作为字符串,而不是regex。你知道吗

这是我的字符串:

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替换两个字符串吗?你知道吗


Tags: oftheto字符串文本goonout
3条回答

这是另一个解决方案(我还使用“非贪婪”修饰符重写regex,将?放在*之后,因为我发现它更可读)。你知道吗

r"\1"引用的组是以parenthises作为未命名的组来完成的。还将re.compile用作样式首选项以减少arg的数量:

line = "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> ."
select_text_regex = re.compile(r"<ERR targ=(.*?)>.*?<\/ERR>")
select_text_regex.sub(r"\1", line)

命名组备选方案:

line = "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> ."
select_text_regex = re.compile(r"<ERR targ=(?P<to_replace>.*?)>.*?<\/ERR>")
select_text_regex.sub(r"\g<to_replace>", line)

您可以在这里找到一些关于组引用的文档:

https://docs.python.org/3/library/re.html#regular-expression-syntax

你需要匹配模式中的目标词,作为一个捕获组-你不能在替换字符串中开始一个全新的搜索!你知道吗

未测试,但这应该可以:

替换r"<ERR targ=(.*?)>.*?</ERR>"

r"\1"

你要找的是正则表达式捕获组。不要选择正则表达式然后尝试用另一个正则表达式替换它,而是将正则表达式中要匹配的部分放在select语句的括号内,然后用\1将其放回替换语句中。(编号为您所包含的组)

line = "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> ."

select_text_regex = r"<ERR targ=([^<]+)>[^<]+<\/ERR>" #Correct Here.
correct_word_regex = r"\1" #And here.

line = re.sub(select_text_regex, correct_word_regex, line.rstrip())

print(line)

相关问题 更多 >