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

to validate the text using the regex which allows one space or hyphen start with 97.

regex: ^97(?=[0-9] [ -]?[0-9] )(?!([0-9])(?:\1|[ -]){2}).{3}$ 

ex: 97123 valid
    97-12 valid but not working as per the above reg 
    971-2 valid  
    9712- not valid 
    

CodePudding user response:

You can use

^(?=[0-9] (?:[ -][0-9] )?$)(?!([0-9])(?:\1|[ -]){2})97.{3}$

See the regex demo

The first lookahead, (?=[0-9] (?:[ -][0-9] )?$), now requires

  • [0-9] - one or more digits
  • (?:[ -][0-9] )? - an optional occurrence of a space or hyphen and then one or more digits
  • $ - end of string

to be present immediately to the right of the current location (that is the start of string).

CodePudding user response:

Your requirements can be covered with this simplified regex:

^97(?=.{3}$)(?:[ -]?\d) $

RegEx Demo

RegEx Breakup:

  • ^: Start
  • 97: Match 97
  • (?=.{3}$): Match 3 more character till end
  • (?:[ -]?\d) : Match an optional hyphen or space followed by a digit. Match this non-capturing group 1 times
  • $: End
  • Related