[英]How to invert an existing regular expression in javascript?
I have created a regex to validate time as follows : ([01]?\\d|2[0-3]):[0-5]\\d
. 我创建了一个正则表达式来验证时间如下:
([01]?\\d|2[0-3]):[0-5]\\d
。
Matches TRUE : 08:00
, 09:00
, 9:00
, 13:00
, 23:59
. 匹配TRUE:
08:00
, 09:00
, 9:00
, 13:00
, 23:59
。
Matches FALSE : 10.00
, 24:00
, 25:30
, 23:62
, afdasdasd
, ten
. 匹配FALSE:
10.00
, 24:00
, 25:30
, 23:62
, afdasdasd
, ten
。
How to invert a javascript regular expression to validate if NOT time? 如何反转javascript正则表达式以验证是否不是时间?
NOTE - I have seen several ways to do this on stack but cannot seem to make them work for my expression because I do not understand how the invert expression should work. 注意 - 我已经看到了几种在堆栈上执行此操作的方法,但似乎无法使它们适用于我的表达式,因为我不理解反转表达式应该如何工作。
http://regexr.com?38ai1 http://regexr.com?38ai1
Simplest solution was to invert the javascript statement and NOT the regex itself. 最简单的解决方案是反转javascript语句而不是正则表达式本身。
if (!(/^(([01]?\\d|2[0-3]):[0-5]\\d)/.test(obj.value))
Simply adding ! 只需添加! to create an if NOT statement.
创建一个if NOT语句。
As i mentioned in the comment, the better way is to negate the test rather then create a new regexp that matches any non-time. 正如我在评论中提到的,更好的方法是否定测试,而不是创建一个匹配任何非时间的新正则表达式。
However, if you really need the regexp, you could use negative lookahead to match the start of something that is not a time: 但是,如果你真的需要正则表达式,你可以使用负前瞻来匹配非时间的东西的开头:
/^(?!([01]?\d|2[0-3]):[0-5]\d$)/
DEMO: http://regex101.com/r/bD3aG4 演示: http : //regex101.com/r/bD3aG4
Note that i anchored the regexp (^ and $), which might not work with what you need it for. 请注意,我锚定了正则表达式(^和$),这可能无法满足您的需要。
A regular expression is usually used for capturing some specific condition(s) - the more specific, the better the regex. 正则表达式通常用于捕获某些特定条件 - 越具体,正则表达式就越好。 What you're looking for is an extremely broad condition to match because just about everything wouldn't be considered "time" (a whitespace, a special character, an alphabet character, etc etc etc).
您正在寻找的是一个非常宽泛的条件,因为几乎所有东西都不会被视为“时间”(空白,特殊字符,字母字符等等)。
As suggested in the comments, for what you're trying to achieve, it makes much more sense to look for a time and then check (and negate) the result of that regular expression. 正如评论中所建议的那样,对于你想要实现的目标,寻找时间然后检查(并否定)正则表达式的结果更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.