簡體   English   中英

在Python中使用正則表達式用另一個字符串替換

[英]Replacing a string with another using regex in Python

我正在嘗試使用正則表達式從所選文本中用單個單詞替換所選文本。 我嘗試了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替換兩個字符串?

這是另一種解決方案(我還通過在*后面加上?來使用“非貪婪”修飾符重寫了正則表達式,因為我認為它更易讀)。

r"\\1"引用的組是用括號作為未命名的組完成的。 還使用re.compile作為樣式首選項來減少args的數量:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM