如何替换不在引号中的字符串 [英] How to replace a string which is not in quotes
问题描述
我在以下场景中苦苦挣扎,我有一个多行字符串,其中多次包含 test 这个词,字符串是:
im struggling with the following scenario, i have a multiline string which has the word test multiple times inside, the string is:
Hello my name is "test" im a test
test is testing
我需要替换所有不在引号中的测试字符串每个找到的字符串都应后跟至少 1 个空格或换行符,而不是其他任何内容,因此上述字符串将转换为:
i need to replace all the test -strings which are not in quotes every of the found ones should be followed by at least 1 whitespace OR a linebreak not by anything else, so the above string would transform into:
Hello my name is "test" im a HELLOWORLD
HELLOWORLD is testing
测试字符串也可以前面加上空格,但也不能没有.
also the test -string could be prepended by whitespaces, but not also without.
我已经发现了一种只替换不在引号内的字符串的方法:
What i already found out is a method to only replace a string which is not inside of quotes:
str.replace(/(test)(?=(?:[^"]|"[^"]*")*$)/, 'HELLOWORLD')
有人可以帮我找出其他规则吗?
could sombebody give me a hand with finding the other rules?
推荐答案
您可以使用:
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
这篇关于如何替换不在引号中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!