当明显没有匹配项时,JavaScript正则表达式测试在控制台中返回“true”

bvjveswy  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(78)

我正在尝试对我在ChatGPT的帮助下编写的JavaScript正则表达式做一个简单的测试(我几乎不知道JavaScript!)。下面是正则表达式:

new RegExp(`(i'm [a-z]+ to ${I_OPINION_WORDS})`, 'i')

一个典型的表达是“我倾向于认为……”
当我用一个不包含“i'm”或“to”的字符串测试它时(“我认为我们应该重新考虑我们用来讨论这个问题的语言。”),测试返回true。有人能帮助我理解这种行为吗?我猜,修改正则表达式以返回false?

const DONT_PHRASES = / dont| don't| do not| can not| cant| can't/;
const PRONOUNS = /he|she|it|they/i;
const PRESIDENT_NAMES = /candidate|clinton|donald|gop|hillary|hilary|trump|trum/i;
const SKIP_WORDS = / also| really| very much/;

const AMBIGUOUS_WORDS = /seemed|prefer/;
const I_OPINION_WORDS = /agree|believe|consider|disagree|hope|feel|felt|find|oppose|think|thought|support/;
const OPINION_PHRASES = /in my opinion|it seems to me|from my perspective|in my view|from my view|from my standpoint|for me/;
const OPINION_PHRASE_REGEXES = [
  new RegExp(`(i(?:${DONT_PHRASES}|${SKIP_WORDS})? ${I_OPINION_WORDS})`, 'i'),
  new RegExp(`(i'm [a-z]+ to ${I_OPINION_WORDS})`, 'i'),
  new RegExp(`(${OPINION_PHRASES},? )`, 'i')
];

const regex = new RegExp(OPINION_PHRASE_REGEXES[1]);
console.log(regex.toString())
console.log(regex.test("I think we should reconsider the language we use to discuss this."));
vwhgwdsa

vwhgwdsa1#

不要使用正则表达式作为插值的一部分,使用字符串或其他东西,如果您查看生成的正则表达式的控制台日志,它看起来不正确。
您还应该使用像regex101这样的工具来测试正则表达式。
接下来,您需要使用一个分组结构()作为您的替代,并使用单词边界(\b)作为reconsidermatchesconsider在没有单词边界的正则表达式中。

/*Use an array to hold the words*/
const A_OPINION_WORDS = ["agree","believe","consider","disagree","hope","feel","felt","find","oppose","think","thought","support"];

/*Use join to generate the regex version, can be done in the string interpolation*/
const I_OPINION_WORDS = A_OPINION_WORDS.join("|");
/*Note the use of () for a capturing group and \b for word boundaries*/
const OPINION_PHRASE_REGEXES = [
  new RegExp(`(i'm [a-z]+ to \b(${I_OPINION_WORDS})\b)`, 'i') 
];

const regex = new RegExp(OPINION_PHRASE_REGEXES[0]);
console.log(regex.toString())
console.log(regex.test("I think we should reconsider the language we use to discuss this."));

你真正应该从中得到的是,总是对AI生成的代码持保留态度,你需要看看它给了你什么,并弄清楚它实际上在做什么。

相关问题