I'm trying to write a regex in which I want to test for 2 things. The string is only valid when it starts with 20 and its length is between 1 and 5, or when it doesn't start with 20 but it still has the plus sign as its first character (example 50) and its length is between 1 and 7 then it's valid too.
Here is what I wrote for this validation :
/^\ (?=20){1,5}|^\ (?!20){1,7}/g
I tested it but it doesn't work how I intended for it and I dont understand why.
CodePudding user response:
What you have is close, but you need to:
- add the character selectors
.to be quantified (.can work to match everything) - constrain the end of the string to prevent the length from going over the max with
$ - can remove
gflag since you only want one match
That leaves you with:
/^\ (?=20).{1,5}$|^\ (?!20).{1,7}$/
which you can also write as
/^\ ((?=20).{1,5}|(?!20).{1,7})$/
CodePudding user response:
You can attempt to match the following regular expression:
^\ (?:20(\D.?)?|(?!20(?!\d)).{0,6})$
The expression can be broken down as follows.
^ # match beginning of string
\ # match ' '
(?: # begin non-capture group
20 # match '20'
(?:\D.?)? # optionally match a non-digit that is optionally
# followed by any character
| # or
(?! # begin negative lookahead
20 # match '20'
(?!\d) # negative lookahead asserts '20' is not followed by a digit
) # end negative lookahead
.{0,6} # match between 0 and 6 characters
) # end non-capture group
$ # match end of string
Note that ' 200' is matched by the second part of the alternation (the string does not begin with '20').
