Home > Mobile >  validate string data using regex which allowed only numbers and - (hyphen) of length 6 but hypen sho
validate string data using regex which allowed only numbers and - (hyphen) of length 6 but hypen sho

Time:07-12

Validate the string using the regex which has the - (hypen)

Requirement is : string contains only digits and - (hyphens) and not end with - (hyphen) and all other digits not be the same.

^([0-9-])(?!\1 $)[0-9-]{5}$

The above one allow only digits and hyphen but its not restricted end with hyphen and check all other digits are same.

ex:

1111-1 Not allowed because all are same digits 
1111-2 Allowed
11112- Not allowed as its end with - Hypen
-12345 Not allowed as its start with - hypen 

CodePudding user response:

You might write the pattern as

^(\d)(?!(?:\1|-) $)(?!\d*-\d*-)[\d-]{4}\d$

Explanation

  • ^ Start of string
  • (\d) Capture a single digit in group 1
  • (?! Negative lookahead
    • (?:\1|-) $ Check that to the right there is not only the group 1 value or hyphens
  • (?!\d*-\d*-) Assert not 2 hyphens
  • ) Close lookahead
  • [\d-]{4} Match 4 digits or hyphens
  • \d Match a digit
  • $ End of string

Regex demo

If there should be at least 1 hyphen:

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

Regex demo

CodePudding user response:

My 2 cents to allow [01] hyphens:

^(?=.{6}$)(\d)(?=.*(?!\1)\d)\d (?:-\d )?$

See an online demo

  • Related