Ela Buwa
Ela Buwa

Reputation: 1704

How to create a matching regex pattern for "greater than 10-000-000 and lower than 150-000-000"?

I'm trying to make

09-546-943

fail in the below regex pattern.

​^[0-9]{2,3}[- ]{0,1}[0-9]{3}[- ]{0,1}[0-9]{3}$

Passing criteria is
greater than 10-000-000 or 010-000-000 and
less than 150-000-000

The tried example "09-546-943" passes. This should be a fail.
Any idea how to create a regex that makes this example a fail instead of a pass?

Upvotes: 0

Views: 205

Answers (3)

virolino
virolino

Reputation: 2227

This pattern:

((0?[1-9])|(1[0-4]))[0-9]-[0-9]{3}-[0-9]{3}

matches the range from (0)10-000-000 to 149-999-999 inclusive. To keep the regex simple, you may need to handle the extremes ((0)10-000-000 and 150-000-000) separately - depending on your need of them to be included or excluded.

Test here.

This regex:

((0?[1-9])|(1[0-4]))[0-9][- ]?[0-9]{3}[- ]?[0-9]{3}

accepts (space) or nothing instead of -.

Test here.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

^(?:(?:0?[1-9][0-9]|1[0-4][0-9])-[0-9]{3}-[0-9]{3}|150-000-000)$

See the regex demo.

The pattern is partially generated with this online number range regex generator, I set the min number to 10 and max to 150, then merged the branches that match 1-8 and 9 (the tool does a bad job here), added 0? to the two digit numbers to match an optional leading 0 and -[0-9]{3}-[0-9]{3} for 10-149 part and -000-000 for 150.

See the regex graph:

enter image description here

Details

  • ^ - start of string
  • (?: - start of a container non-capturing group making the anchors apply to both alternatives:
    • (?:0?[1-9][0-9]|1[0-4][0-9]) - an optional 0 and then a number from 10 to 99 or 1 followed with a digit from 0 to 4 and then any digit (100 to 149)
    • -[0-9]{3}-[0-9]{3} - a hyphen and three digits repeated twice (=(?:-[0-9]{3}){2})
  • | - or
    • 150-000-000 - a 150-000-000 value
  • ) - end of the non-capturing group
  • $ - end of string.

Upvotes: 4

Emma
Emma

Reputation: 27763

This expression or maybe a slightly modified version of which might work:

^[1][0-4][0-9]-[0-9]{3}-[0-9]{3}$|^[1][0]-[0-9]{3}-[0-9]{2}[1-9]$

It would also fail 10-000-000 and 150-000-000.

In this demo, the expression is explained, if you might be interested.

Upvotes: 0

Related Questions