繁体   English   中英

用于在字符串中查找模式的 Javascript 正则表达式,排除可能的前面单词匹配

[英]Javascript regex to find a pattern in a string, excluding a possible preceding word match

变量中有一个文字/文本字符串:

var copypaste, replaced;
var verbdb = ["keep","know","enjoy"];
var arrayLength = verbdb.length;

for (var i = 0; i < arrayLength; i++) {
    copypaste = "One of the reasons first_name keep waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy being challenged and blah blah blah.";

    replaced = copypaste.replace(RegExp("[^let]? first_name " + verbdb[i] + "(\s|\.)","g")," first_name " + verbdb[i] + "_object_s\$1");
}

我试图从replaced变量中得到的是仅当 first_name 前面有let一词时才排除。

“first_name keep_object_s 晚上醒来的原因之一,是等等等等。试试这个,让 first_name 知道,看看等等等等。记住 first_name enjoy_object_s 受到挑战,等等等等。”;


所以在这个例子中:

  1. 第一个模式匹配(保持)并替换为添加的_object_s
  2. 由于“让”这个词,第二个模式不匹配(知道),所以没有替换
  3. 第三个模式 MATCHES (enjoy) 并替换为添加的_object_s

你可以试试这个:

(?:\b)(?!let)(?=\w+\sfirst_name\s+(know|keep|enjoy))(\w+ \w+)\s+(\w+)

解释

 const regex = /(?:\\b)(?!let)(?=\\w+\\sfirst_name\\s+(know|keep|enjoy))(\\w+ \\w+)\\s+(\\w+)/g; const str = `One of the reasons first_name keep waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy being challenged and blah blah blah`; const subst = `$2 _object_s`; const result = str.replace(regex, subst); console.log(result);

暂无
暂无

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

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