[英]JavaScript regular expression to negate an exact string match
Is there a way in HTML (JavaScript) to write a regular expression to negate an exact string match? HTML(JavaScript)中是否有一种方法可以编写正则表达式来否定精确的字符串匹配?
I would like to make sure an input is not equal to " foo
". 我想确保输入不等于“
foo
”。 Only " foo
" must fail validation, but " fooo
" must be allowed. 只有“
foo
”必须通过验证,但必须允许“ fooo
”。
In other words, I'm looking for a negation of this regex: 换句话说,我正在寻找对这个正则表达式的否定:
<input pattern="^foo$" ...>
One possible way is combining start of string anchor ( ^
) with negative lookahead that includes both the target string and end of string anchor ( $
): 一种可能的方法是将字符串锚点(
^
)的开头与包含目标字符串和字符串锚点结尾( $
)的负前瞻相结合:
/^(?!foo$)/
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. 但是
pattern
模式在该帐户中很有趣 - 它必须匹配字符串中的某些内容,这就是原始方法不起作用的原因。 This does work, however: 但这确实有效:
<input pattern="(?!foo$).*">
你可以使用这个正则表达式:
\bfooo\b
If Javascript is allowed, why not just negate the result of the match? 如果允许Javascript,为什么不否定匹配的结果呢?
if (!yourString.match(/^foo$/)) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.