简体   繁体   中英

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 .

Matches TRUE : 08:00 , 09:00 , 9:00 , 13:00 , 23:59 .

Matches FALSE : 10.00 , 24:00 , 25:30 , 23:62 , afdasdasd , ten .


QUESTION

How to invert a javascript regular expression to validate if NOT time?

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


ANSWER

Simplest solution was to invert the javascript statement and NOT the regex itself.

if (!(/^(([01]?\\d|2[0-3]):[0-5]\\d)/.test(obj.value))

Simply adding ! to create an if NOT statement.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM