Home > Mobile >  how to create a regular expression to validate the numbers are not same even separated by hyphen (-)
how to create a regular expression to validate the numbers are not same even separated by hyphen (-)

Time:05-06

Using the following regex

^(\d)(?!\1 $)\d{3}-\d{1}$

It works for the pattern but I need to validate that all numbers are not the same even after /separated by the hyphen (-).

Example:

0000-0 not allowed (because of all are same digits)
0000-1 allowed
1111-1 not allowed (because of all are same digits)
1234-2 allowed

CodePudding user response:

TheFourthBird's answer surely works that uses a negative lookahead. Here is another variant of this regex that might be slightly faster:

^(\d)(?!\1{3}-\1$)\d{3}-\d$

RegEx Demo

Explanation:

  • ^(\d) matches and captures first digit after start in group #1
  • (?!\1{3}-\1$) is a negative lookahead that will fail the match if we have 3 repetitions and a hyphen and another repeat of 1st digit.

CodePudding user response:

You could exclude only - or the same digit only to the right till the end of the string:

^(\d)(?!(?:\1|-)*$)\d{3}-\d$
  • ^ Start of string
  • (\d) Capture group 1, match a digit
  • (?! Negative lookahead, assert what is to the right is not
    • (?:\1|-)*$ Optionally repeat either the backrefernce to what is already captured or - till the end of the string
  • ) Close the non capture group
  • \d{3}-\d Match 3 digits - and a digit
  • $ End of string

Regex demo

If you don't want to match double -- or an - at the end of the string and match optional repetitions:

^(\d)(?!(?:\1|-)*$)\d*(?:-\d )*$

Explanation

  • ^ Start of string
  • (\d) Capture a single digits in group 1
  • (?!(?:\1|-)*$) Negative lookahead, assert not only - and the same digit till the end of the string
  • \d* Match optional digits
  • (?:-\d )* Optionally repeat matching - and 1 digits
  • $ End of string

Regex demo

CodePudding user response:

You'll need a back reference, for example:

^(\d){4}-\1$
  • Related