Home > Software engineering >  Regular expression to validate the given input which accepts one space or Hyphen which is part of th
Regular expression to validate the given input which accepts one space or Hyphen which is part of th

Time:09-27

In the below example, I am validating the 4 characters' text with include either one space or Hyphen (-) or without that also only 4 characters.

Regex : ^[A-Z0-9]{4}$|(?=^.{4}$)^[A-Z0-9] [- ]?[A-Z0-9] $ 

It worked the cases as below cases but it failed to validate the text contains all same characters like 1111, AAAA is not allowed

1234  valid
12-4  valid
12 4  valid  
1111  invalid ( as all are the same characters)
11-1  invalid ( as all are the same characters)
12345 invalid

CodePudding user response:

You can use this regex to match your strings:

^(?=[A-Z0-9] [ -]?[A-Z0-9] )(?!([A-Z0-9])(?:\1|[ -]){3}).{4}$

Regex explanation:

  • ^ start of string
  • (?=[A-Z0-9] [ -]?[A-Z0-9] ) asserts that the string consists of one or more of A-Z0-9, an optional or -, and one or more of A-Z0-9
  • (?!([A-Z0-9])(?:\1|[ -]){3}) asserts that the first character is not repeated in every position where there is a character
  • .{4}$ matches only 4 characters between start and end of string

Demo on regex101

  • Related