Reputation: 1555
I've got a scenario as follows. Our systems needs to pull filters from a string passed in as a query parameter, but also throw a 404 error if the string isn't correctly formatted. So let's take the following three strings as an exmple:
By the application requirements, only #3 is supposed to match as a "valid" string. So my current regex to match that is /([a-z]+)(\d+)/
. But this also matches #1, if not entirely, but it still matches.
My problem thus is twofold - I need 2 patterns, 1 that will match only the 3rd string in this list, and another that will match the "not-acceptable" strings 1 and 2. I believe there must be some way to "negate" a pattern (so then I'd technically only need one pattern, I'm assuming), but I'm not sure how exactly to do that.
Thanks for any help!
EDIT
For clarity's sake, let me explain. The "filter parameters" present here take the following structure - 1 or 2 letters, followed by a number of, well, numbers. That structure can repeat itself however many times. So for example, valid filter strings could be
Invalid strings could be
Upvotes: 1
Views: 59
Reputation: 36101
After clarifying the question:
^([a-zA-Z]{1,2}\d+)*$
Explanation:
[a-zA-Z]
- a lower or upper case letter{1,2}
- one or two of those\d+
- one or more digits()*
- the whole thing repeated any number of times^$
- match the entire string from start(^
) to end($
)Upvotes: 4
Reputation: 784998
You can use this regex for valid input:
^([a-zA-Z]+\d+)+$
To find invalid inputs use:
^(?!([a-zA-Z]+\d+)+$).+$
Upvotes: 2
Reputation: 6800
/^(?:(?:[a-z]+)(?:\d+))*$/
You were hella close, man. Just need to repeat that pattern over and over again till the end.
Change the *
to a +
to reject the empty string.
Oh, you had more specific requirements, try this:
/^(?:[a-z]{1,2}\d+)*$/
Broken down:
^ - Matches the start of the string an anchor
(?: - start a non-capturing group
[a-z] - A to Z. This you already had.
{1,2} - Repeat 1 or 2 times
\d+ - a digit or more You had this, too.
)* - Repeat that group ad nauseum
$ - Match the end of the string
Upvotes: 1
Reputation: 360592
If you only want digits at the end of the string, then
/\d$/
would do. \d
= digit, $
= end of string.
Upvotes: 0