简体   繁体   中英

Regex validation phone number with brackets optional characters not working

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

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

^[+|(|\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM