[英]RegEx for replacing specific words not between quotation marks
我试图用另一个单词替换字符串s
Hello
,如果单词不在引号之间,如“”或“'。 让我们假装替换词是马特所以,
这是输入:
s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'
期望的输出:
s = 'Matt How are you, "hey Hello", \'ney Hello\'. Matt I\'m great '
我已经四处搜索并遇到了这些代码,只需稍加修改我就能成功替换这个词,但它只适用于''而不是'“包括在内
import re
def replace_method(match):
if match.group(1) is None:
return match.group()
return match.group().replace("Hello", "Matt")
s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'
output = re.sub(r"'[^']*'|([^']*)", replace_method, s)
print(output)
编辑:
谢谢你的回答,但我错过了解释一些重要的事情(我在第一次注意到,在我的辩护中,在执行成功的代码之后),“显然”我不想要这句话:
s = "Hellona, how are you"
成为
s = "Markna, how are you"
所以,正则表达式应该包括我试图替换的单词不是由数字或字母 surronded。
替换回调看起来很好。
然而,正则表达式需要是这样的
r"('[^']*'|\\"[^\\"]*\\")|\\b[Hh]ello\\b"
可读版本
( # (1 start)
' [^']* '
|
" [^"]* "
) # (1 end)
|
\b [Hh]ello \b
请注意,我认为组1检入回调
如果组1匹配则必须为真。
不是Python程序员,但它应该是类似的东西
if match.group(1) :
return match.group()
return "Matt"
import re
def replace_word(input, search, replace):
def replace_method(match):
if match.group(2) is None:
return match.group()
return match.group(2).replace(search, replace)
expr = re.compile("('[^']*'|\"[^\"]*\")|({})".format(search))
return re.sub(expr, replace_method, s)
s = 'Hello How Are you, "hey Hello", \'ney Hello\'. Hello I\'m great'
output = replace_word(s, "Hello", "Matt")
print(output)
您可以匹配组1中的单引号或双引号之间的所有内容( ('[^']*'|\\"[^\\"]*\\")
),然后您在第2组( {}
使用search
词格式化的单词),然后用你想要的任何东西替换第2组。
在这里,我们可以用以下方法解决这个问题:
([^'"]?)(Hello)([^'"])
我们可以用它替换它:
如果不需要此表达式,则可以在regex101.com中修改/更改表达式。
您还可以在jex.im中可视化表达式:
此代码段显示我们可能有一个有效的表达式:
const regex = /([^'"]?)(Hello)([^'"])/gm; const str = `Hello How Are you, "hey Hello", 'ney Hello'. Hello I'm great. "Hello' I'm great`; const subst = `$1Matt$3`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([^'\"]?)(Hello)([^'\"])"
test_str = "Hello How Are you, \"hey Hello\", 'ney Hello'. Hello I'm great. \"Hello' I'm great"
subst = "\1Matt\3"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
为了排除Hellona
,我们可以添加一个单词边界:
([^'"]?)(\bHello\b)([^'"])
const regex = /([^'"]?)(\\bHello\\b)([^'"])/gm; const str = `Hello How Are you, "hey Hello", 'ney Hello'. Hello I'm great. "Hello' I'm great. Hellona how are you? `; const subst = `$1Matt$3`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.