Home > other >  Regex validation phone number with brackets optional characters not working
Regex validation phone number with brackets optional characters not working

Time:08-26

I am working on a validation with Regex and the condition is below

 1(061)235-663 - valid
1(061)235-663 - valid
(061)235-663 - valid

The regex I am trying is below

val regex = """\d{3}([-.])\d{3}\1\d{4}|\d{10}|^(\ 1|1)?(\(\d{3}\)\d{3}\-\d{3})$""".toRegex()

our focus is on last part : ^(\ 1|1)?(\(\d{3}\)\d{3}\-\d{3})

I am not able to escape 1. other cases are working. So the scenario is like that, 1 and 1 is optional.

It seems like back slash not working as escape character in kotlin Regex

CodePudding user response:

not sure what you need to catch, but if you add a second group, you will only match the number (061)235-663

^(\ 1|1)?(\(\d{3}\)\d{3}\-\d{3})

see Regex101

CodePudding user response:

^[ |(|\d]?[\d|(|\s|] [)|\s] \d [-|\s] \d 

logic used is

  1. starting with or "(" or a digit
  2. second char is "(" or space or digit. it can be of any length, if you need 3 u can limit
  3. next stop is either at ")" or space
  4. then followed by numbers of any length
  5. then followed by "-" or space
  6. then followed by digits.

these can be used just as direction to what finally you need. https://regex101.com/r/GKlnoz/1

  • Related