如何替换不在引号中的字符串

How to replace a string which is not in quotes

本文关键字:字符串 何替换 替换      更新时间:2023-09-26

im在以下场景中挣扎,我有一个多行字符串,里面有多次单词test,字符串是:

Hello my name is "test" im a test
test is testing

我需要替换所有不在引号中的测试字符串每个找到的字符串后面都应该至少有1个空格或换行符,而不是其他任何字符,所以上面的字符串将转换为:

Hello my name is "test" im a HELLOWORLD
HELLOWORLD is testing

测试字符串也可以用空格作为前缀,但也不能没有空格。

我已经发现了一种只替换不在引号内的字符串的方法:

str.replace(/(test)(?=(?:[^"]|"[^"]*")*$)/, 'HELLOWORLD')

森博迪能帮我找到其他规则吗?

('btest'b)(?=(?:[^"]|"[^"]*")*$)

试试这个。请参阅演示。

https://regex101.com/r/pT4tM5/28

您可以使用:

var str = 'Hello my ''test'' name is "test" im a test'ntest is testing';
var repl = str.replace(/("[^"]*"|'[^']*')|'btest'b/g, function($0, $1) { 
           return ($1 == undefined) ? "HELLOWORLD" : $1; });

输出:

Hello my 'test' name is "test" im a HELLOWORLD
HELLOWORLD is testing