我使用这段代码的目标是只替换出现在特定模式之前和之后的子字符串(为了建立该模式,我使用了regEx)
实际上,我已经try 了很多方法,但没有得到好的结果,这里我使用compile()
方法将输入字符串中找到的RegEx模式编译成一个regex模式对象(基本上我逐个提取我想要修改的满足RegEx模式条件的子字符串的匹配项).
然后,我可以简单地使用replace()
函数,原谅冗余,将提取的子串替换为我想要的子串
import re
input_text = "y creo que hay 55 y 6 casas, y quizas alguna mas... yo creo que empezaria entre la 1 ,y las 27"
#the string with which I will replace the desired substrings in the original input string
content_fix = " "
##This is the regex pattern that tries to establish the condition in which the substring should be replaced by the other
#pat = re.compile(r"\b(?:previous string)\s*string that i need\s*(?:string below)?", flags=re.I, )
#pat = re.compile(r"\d\s*(?:y)\s*\d", flags=re.I, )
pat = re.compile(r"\d\s*(?:, y |,y |y )\s*(?:las \d|la \d|\d)", flags=re.I, )
x = pat.findall(input_text)
print(*map(str.strip, x), sep="\n") #it will print the substrings, which it will try to replace in the for cycle
content_list = []
content_list.append(list(map(str.strip, x)))
for content in content_list[0]:
input_text = input_text.replace(content, content_fix) # "\d y \d" ---> "\d \d"
print(repr(input_text))
这是我得到的输出:
'y creo que hay 5 casas, y quizas alguna mas... yo creo que empezaria entre la 7'
这是the correct output that I need:
'y creo que hay 55 6 casas, y quizas alguna mas... yo creo que empezaria entre la 1 27'
我应该对RegEx进行哪些更改,以使其提取正确的子字符串并符合此代码的目标?