我正在寻找一种方法来替换一个单词,但是只有当它没有被引号包围时。
例如
用Hello
Hi
Hello 'Hello' Nothing
→Hi 'Hello' Nothing
由于'Hello'
在引号中,它不会被替换,但第一个Hello
会这样做,因为它没有用引号括起来。
任何帮助都会很棒!
答案 0 :(得分:3)
正则表达式很棒:
>>>import re
>>>expression = re.compile("(?!(\"|'))Hello(?!(\"|'))")
>>>expression.sub("Hi",'This string says "Hello" and Hello')
This string says "Hello" and Hi
唯一的问题是它也无法替换“Hello和Hello”,如果这成为一个问题,你可以为它们添加特定的案例。
答案 1 :(得分:1)
考虑使用a regular expression(不是唯一的方法,但我会继续使用)。
In [2]: print s
Hello 'Hello' Nothing
In [3]: import re
In [4]: re.sub("(?<!')Hello(?!')", 'Hi', s)
Out[4]: "Hi 'Hello' Nothing"
答案 2 :(得分:1)
使用正则表达式:
>>> import re
>>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "Hello mate")
'Hi mate'
>>> re.sub(r'([^"\']|^)Hello([^"\']|$)', r'\1Hi\2', "'Hello' mate")
"'Hello' mate"
'([^"\']|^)Hello([^"\']|$)'
表示'字符串 Hello 包围的内容不同于单引号或双引号,或者在行的开头或结尾处'。
答案 3 :(得分:0)
试试这个:
import re
def callback(match):
rep = 'Hi'
return match.group(1)+rep+match.group(2)
your_string = "Hello 'Hello' Nothing"
print re.sub("([^\']|^)Hello([^\']|$)", callback, your_string)
这将匹配除Hello
之外的任何内容所包含的单词'
(^
中的[]
表示除了之外的任何内容)。我还添加了|^
和|$
以匹配字符串末尾或开头的单词Hello
。
它将用括号中的第一部分和Hi和第二部分(无论它们是什么)替换它。
答案 4 :(得分:0)
使用substring函数查找要替换的单词的所有出现,为每个单词查看substring函数返回之前的一个索引,并查看它是否为引号。
例如。 “”你好'你好'没什么“
子串函数返回0 - 所以当然没有引用 子串函数返回6 - 检查字符串[5] - 这是一个引用,寻找下一个ocurance
如何使用子字符串函数继续检查?像这样的东西:
startindex=0
while(!done):
index=substr(string, startindex)
if(str[index-1] == "'")
startindex=index
continue
从这里你可以搞清楚
答案 5 :(得分:0)
这适用于您的测试用例。
import re
foo = "Hello 'Hello' Nothing"
mt = re.search(r"[^']Hello(\s+.*)", foo)
if mt:
foo = 'Hi' + match.group(1)