javascript – How can i make my regex only accept a closing parentheses if it already matched an opening one
In the pattern [(]?[0-9]{3}[)]?, the opening and closing brackets are optional. There is no relationship between those to optional brackets. So, it will match 012, (012, 012) and (012).
Regex cannot “remember” whether it found a bracket before or not. So, if you only want to match a closing bracket when you got an opening one, you have to explicitly distinguish between the following two patterns:
- there is an opening bracket, 3 numbers and a closing bracket (
[(][0-9]{3}[)]), or - there are only 3 numbers (
[0-9]{3}).
This translates to the following regex: ([(][0-9]{3}[)]|[0-9]{3}). The complete regex then looks as follows:
const validNumbers = /^[1]? ?([(][0-9]{3}[)]|[0-9]{3})\s?[0-9]{3}[-\s]?[0-9]{4}$/i
For your test string, we get the following:
>>> console.log(validNumbers.test("1 305) 9759003"))
false
>>> console.log(validNumbers.test("1 (305) 9759003"))
true
Read more here: Source link
