在JS中是否可以定义regexp,当在输入结束时对给定文本进行测试时,该regexp会给出false

Is it possible in JS to define regexp that would give false when testing on given text in the end of input?

本文关键字:regexp 文本 false 测试 结束 是否 JS 输入 定义      更新时间:2023-09-26

我需要JS中的regexp模式,当在输入结束时对给定文本进行测试时,该模式会给出false。例如:

/(?!not this text)$/.test("blablabla not this text") === false
/(?!not this text)$/.test("blablabla     this text") === true

但那样不行!以下是一些实验:

console.log("<expected>: <actual>");
console.log("false:"  + /^(?!<asd>)/.test("<asd>"));
console.log("true:"   + /^(?!<asd>)/.test("<asg>"));
console.log("false:"  + /(?!<asd>)$/.test("<asd>"));
console.log("true:"   + /(?!<asd>)$/.test("<asg>"));
console.log("false:"  + /(<asd>){0}$/.test("<asd>"));
console.log("true:"   + /(<asd>){0}$/.test("<asg>"));

输出:

<expected>: <actual>
false:false
true:true
false:true
true:true
false:true
true:true

问题:JS中是否可以定义regexp,当在输入结束时对给定文本进行测试时,该regexp会给出false?

是的,有可能:

/^(?:(?!not this text$).)*$/

请注意,正则表达式必须锚定在两端,前瞻子表达式必须锚定在末尾而不是开头。

另一种方法是:

/^(?!.*not this text$).*$/

同样,正则表达式作为一个整体必须锚定在两端才能工作。

如果这是唯一的测试,那么:

if (!/not this text$/.test(str));