除非发现某个值是引用文本的一部分,否则如何删除它的所有实例? [英] How can I remove all instances of a certain value unless it is found to be part of quoted text?

查看:14
本文介绍了除非发现某个值是引用文本的一部分,否则如何删除它的所有实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using regular expressions, I want to remove all instances of a certain value unless the value is part of quoted text when it is found.

例如,如果我想删除book这个词,除非它在引号中,并且我有以下文本:

For example, if I want to remove the word book unless it is found in quotes, and I have the following text:

telephone book computer "i read a book" keyboard book

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

How can I use regular expressions to make it appear as:

telephone computer "i read a book" keyboard

使用 string.replace 的 WebKit JavaScript 正则表达式是否可以做到这一点?

Is this possible with WebKit JavaScript regex using string.replace?

推荐答案

您可以借助 回调 (演示):

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

或者在前瞻技巧的帮助下(演示):

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

最后一个只在引号总是闭合的情况下才有效,对于长字符串可能效率不高.

Last one only only works if quotes are always closed, and may not be efficient for long strings.

这篇关于除非发现某个值是引用文本的一部分,否则如何删除它的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆