[英]Regex - Replace only if the pattern is not inside a quote
Lets say i want to write a regular expression to replace the word Dog
with the word Cat
.假设我想写一个正则表达式来用单词
Cat
替换单词Dog
。
eg例如
Dogs are scary.
will become:会变成:
Cats are scary.
But i want this regex to be applied only if the word Dog is not inside a quote.但我希望只有在单词 Dog 不在引号内时才应用此正则表达式。
eg例如
Dogs are scary but my mom told me that "Dogs are cute"
will become:会变成:
Cats are scary but my mom told me that "Dogs are cute"
I have no idea how to do it.我不知道该怎么做。 Help me please :)
请帮帮我 :)
If you're running perl or php you could use the below regex which uses the PCRE verb (*SKIP)(*F)
如果您正在运行perl或php,则可以使用下面的正则表达式,该正则表达式使用PCRE动词
(*SKIP)(*F)
"[^"]*"(*SKIP)(*F)|Dog
Then replace the matched Dog
string with Cat
然后将匹配的
Dog
字符串替换为Cat
You can use this regex for search: 您可以使用此正则表达式进行搜索:
(?=(([^"]*"){2})*[^"]*$)Dogs
And replace by: 并替换为:
Cats
It matches text only if outside quote -- ie match even number of quotes after keyword dogs
. 它仅在引号外匹配文本,即匹配关键字
dogs
后的双引号。
Dogs(?=(?:[^"]*"[^"]*")*[^"]*$)
Try this.Replace by cat
.See demo. 试试看。用
cat
代替。请参阅演示。
https://regex101.com/r/dU7oN5/25 https://regex101.com/r/dU7oN5/25
对于更完整的功能,如果您需要变量来控制替换,请参阅https://stackoverflow.com/a/69428257/1432181了解类似问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.