Home > database >  Regex to validate the number which include max one hyphen (-) but that is exclude from the count of
Regex to validate the number which include max one hyphen (-) but that is exclude from the count of

Time:07-29

Regex to validate the number which include max one hyphen (-) but that is exclude from the count of characters

Four digits are allowed with just one hyphen between them.

The example below regular expression also counts the hyphen in for the number of characters:

^(?!\D*(\d)(?:\D*\1) \D*$)(?=.{4}$)[0-9]*(?:-[0-9]*){0,1}[0-9] $

The above one validate the 1112 as its 4 digits, but it will fail 111-2 because there is one hyphen and five digits, which is not allowed.

Examples:

  • 1234 allowed as its 4 digits
  • 123-4 allowed as we need to skip the hyphen for the count
  • 1111 is not allowed as the same digits are used in the string
  • 111-1 not allowed as the digits are the same, even separated by hyphen -.

CodePudding user response:

You can use

^(?!\D*(\d)(?:\D*\1) \D*$)(?=(?:\D*\d){4}\D*$)[0-9] (?:-[0-9] )?$

See the regex demo. Details:

  • ^ - start of string
  • (?!\D*(\d)(?:\D*\1) \D*$) - the string cannot contain identical digits regardless of any non-word chars present in string
  • (?=(?:\D*\d){4}\D*$) - a positive lookahead that requires four occurrences of any zero or more non-digits followed with a digit, and then any zero or more non-digits till end of string
  • [0-9] (?:-[0-9] )? - one or more digits, and then an optional occurrence of a - and one or more digits
  • $ - end of string.
  • Related