gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:55:58 25 4
gpt4 key购买 nike

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

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.";


所以在这个例子中:

  1. 第一个模式匹配(保留)并替换为添加的_object_s
  2. 第二个模式不匹配(知道)因为单词“let”,所以没有替换
  3. 第三个模式匹配(享受)并替换为添加的_object_s

最佳答案

你可以试试这个:

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

Explanation

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com