简体   繁体   English

Javascript:替换干草堆中不位于两个字符之间的needle

[英]Javascript: Replace needle in haystack that is not between two characters

I'd like to replace a needle in a haystack that is not between two characters. 我想更换一个不在两个字符之间的大海捞针。

So say I have a regular expression that is /\\bneedle\\b/g , that will match all needle's that are not next to any word character. 假设我有一个正则表达式/\\bneedle\\b/g ,它将匹配所有不在任何单词字符旁边的needle。 I want to expand on this and include needle's that are not next to any word character, and NOT between two characters such as [ and ] 我想对此进行扩展,并包括不与任何单词字符相邻的针,并且不要在诸如[和]之类的两个字符之间

So the first three needles will match but the rest will not: needle: needle's needle [needle] [needle something] needle1 needler 因此,前三根针将匹配,而其余三根将不匹配: needle: needle's needle [needle] [needle something] needle1 needler

Any idea how I'd go about doing this? 知道我该怎么做吗?

You can use this regex: 您可以使用此正则表达式:

/(^|[^\w\[])(needle)(?![\w\]])/

RegEx Demo 正则演示

Breakup: 分手:

(^|[^\w\[])    # line start OR a non-word non-[ character
(needle)       # match and group our targeted text
(?![\w\]])     # negative lookahead to fail the match if next char is word char or [

As per comments below you can use following replace code: 根据下面的注释,您可以使用以下replace代码:

var str = "needle: needle's needle [needle] [needle something] needle1 needler";
var reg = new RegExp("(^|[^\\w\\[])(needle)(?![\\w\\]])", "gi");
str = str.replace(reg, "$1*$2*");

//=> *needle*: *needle*'s *needle* [needle] [needle something] needle1 needler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM