我想使用正则表达式删除某个值的所有实例,除非找到该值是引用文本的一部分。

例如,如果我想删除单词书,除非在引号中找到它,并且我有以下文本:

telephone book computer "i read a book" keyboard book


如何使用正则表达式使其显示为:

telephone computer "i read a book" keyboard


使用string.replace的WebKit JavaScript正则表达式可能吗?

最佳答案

您可以在回调(demo)的帮助下完成此操作:

result = str.replace(/\bbook\b\s*|("[^"]*")/g, function(m, quotes){ return quotes ? quotes: '' });


或借助(demo)之类的先行技巧:

result = str.replace(/\bbook\b\s*(?=[^"]*(?:"[^"]*"[^"]*)*$)/g, '');


最后一个仅在引号始终关闭且对长字符串可能无效的情况下才有效。

10-08 08:57
查看更多