本文介绍了JavaScript 正则表达式否定精确的字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 HTML (JavaScript) 中有没有办法编写正则表达式来否定精确的字符串匹配?

Is there a way in HTML (JavaScript) to write a regular expression to negate an exact string match?

我想确保输入不等于foo".只有foo"必须验证失败,但必须允许fooo".

I would like to make sure an input is not equal to "foo". Only "foo" must fail validation, but "fooo" must be allowed.

换句话说,我正在寻找这个正则表达式的否定:

In other words, I'm looking for a negation of this regex:

推荐答案

一种可能的方法是将字符串锚点的开头 (^) 与包含目标字符串和字符串结尾锚点的负前瞻结合起来($):

One possible way is combining start of string anchor (^) with negative lookahead that includes both the target string and end of string anchor ($):

/^(?!foo$)/

演示.

但是 pattern 模式在那个帐户中很有趣 - 它必须匹配字符串中的某些内容,这就是原始方法不起作用的原因.但是,这确实有效:

But pattern pattern is funny in that account - it has to match something in the string, that's why the original approach doesn't work. This does work, however:

<input pattern="(?!foo$).*">

这篇关于JavaScript 正则表达式否定精确的字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:20