How to replace a string which is not in quotes

╄→尐↘猪︶ㄣ 提交于 2019-12-11 08:06:19

问题


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

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?


回答1:


You can use:

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; });

Output:

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



回答2:


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

Try this.See demo.

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



来源:https://stackoverflow.com/questions/29170998/how-to-replace-a-string-which-is-not-in-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!