iLikeBreakfast
iLikeBreakfast

Reputation: 1555

Match string that doesn't have number after letter

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:

  1. pf0pt1000r
  2. pfasdfadf
  3. pf2000pt2100

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

Answers (4)

ndnenkov
ndnenkov

Reputation: 36101

After clarifying the question:

^([a-zA-Z]{1,2}\d+)*$

Explanation:

  1. [a-zA-Z] - a lower or upper case letter
  2. {1,2} - one or two of those
  3. \d+ - one or more digits
  4. ()* - the whole thing repeated any number of times
  5. ^$ - match the entire string from start(^) to end($)

Upvotes: 4

anubhava
anubhava

Reputation: 784998

You can use this regex for valid input:

^([a-zA-Z]+\d+)+$

RegEx Demo 1

To find invalid inputs use:

^(?!([a-zA-Z]+\d+)+$).+$

RegEx Demo 2

Upvotes: 2

FrankieTheKneeMan
FrankieTheKneeMan

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

Marc B
Marc B

Reputation: 360592

If you only want digits at the end of the string, then

/\d$/

would do. \d = digit, $ = end of string.

Upvotes: 0

Related Questions