Harinatha Reddy
Harinatha Reddy

Reputation: 155

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

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:

Upvotes: 0

Views: 345

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

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.

Upvotes: 1

Related Questions