Home > Back-end >  How to create regex pattern with OR condition
How to create regex pattern with OR condition

Time:06-18

I need a pattern that would accept

  1. minimun two characters and only numbers OR
  2. only numbers with dash in third position and first two numbers should be either 56 or 78. So if there is dash then there should be 56 or 78 next to it

Valid matches:

12
123456789
423432423423423423423432
56-1
56-23456789
78-12
78-34234234234234234234234

Invalid matches:

1
1-
11-
1-112
44-2342424
64-4345334
55-sdrfewrwe
56-
5678-234324123423154

Here is my pattern so far:

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

CodePudding user response:

You can use

^(?:(?:56|78)-[0-9] |[0-9]{2,})$

See the regex demo.

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group with two alternatives:
    • (?:56|78)-[0-9] -56or78, -`, one or more digits
    • | - or
    • [0-9]{2,} - two or more digits
  • ) - end of the group
  • $ - end of string.

CodePudding user response:

How about that idea...

^(?:56-|78-|\d)\d $

See this demo at regex101

  • Related