JS 中是否可以定义在输入末尾给定文本进行测试时给出 false 的正则表达式?

发布于 2024-12-27 20:42:48 字数 886 浏览 3 评论 0原文

我需要 JS 中的正则表达式模式,当在输入末尾测试给定文本时,该模式会给出 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 中是否可以定义在输入末尾给定文本进行测试时给出 false 的正则表达式?

I need a regexp pattern in JS that that would give false when testing on given text in the end of input.
For example:

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

But it won't work that way! Here's some experiment:

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

Gives output:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贱贱哒 2025-01-03 20:42:48

是的,这是可能的:

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

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

另一种方法是:

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

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

Yes, it's possible:

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

Note that the regex must be anchored at both ends, and the lookahead subexpression must be anchored at the end but not at the beginning.

Another way to do it is:

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

Again, the regex as a whole has to be anchored at both ends for this to work.

未央 2025-01-03 20:42:48

如果这是唯一的测试,只需:

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

If this is the only test, just:

if (!/not this text$/.test(str)); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文