变量中有一串文字/文本:
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
时才排除。
"One of the reasons first_name keep_object_s waking up at night, is blah blah blah. Try this, let first_name know and see blah blah blah. Remember that first_name enjoy_object_s being challenged and blah blah blah.";
所以在这个例子中:
- 第一个模式匹配(保留)并替换为添加的
_object_s
, - 第二个模式不匹配(知道)因为单词“let”,所以没有替换
- 第三个模式匹配(享受)并替换为添加的
_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);
关于用于在字符串中查找模式的 Javascript 正则表达式,不包括可能的前面单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41689326/