Home > database >  Find 2 or more parentheses in string using Regex
Find 2 or more parentheses in string using Regex

Time:01-16

I am working on the Free Code Camp Javascript phone number validation project. There is a phone number that I need to pass through my code to change to proper formatting that contains more than 1 set of parentheses: (555)5(55?)-5555.

How do I match 2 or more instances of each type of parentheses? For example, I want to find 2 or more instances of "(" or 2 or more instances of ")" anywhere in the string.

I tried the following regex and it did not work: /\({2,}|\){2,}/

Thanks in advance for any guidance, I am very new to Regex.

CodePudding user response:

You can use /\(.*?\)/g to get the match and then use length to get the count.

enter image description here

const str = '(555)5(55?)-5555';
const result = str.match(/\(.*?\)/g)?.length;
if (result >= 2) console.log('Valid');
else console.log('Not Valid');

The above will still pass the test if you are testing against const str = '()5555(55?)-5555';

In that case you can use /\(. ?\)/g as:

enter image description here

const str = '()5555(55?)-5555';
const result = str.match(/\(. ?\)/g)?.length;
if (result >= 2) console.log('Valid');
else console.log('Not Valid');

CodePudding user response:

I want to find 2 or more instances of "(" or 2 or more instances of ")" anywhere in the string.

Are you sure this is what you mean? Intuitively it feels more likely that you would want to find 2 closed parenthesis groups. In this case you could do something like in the previous answer, although you could do it in a single regex with:

(?:.*\(.*\)){2}

https://regex101.com/r/ldaCf4/1

I want to find 2 or more instances of "(" or 2 or more instances of ")" anywhere in the string.

If this is actually what you want, as another previous answer pointed out it is perhaps not an ideal place to use a regex and it might be much clearer and simpler to use the count method, but you could do it with a regex using:

.*(?:\(.*){2}|.*(?:\).*){2}

https://regex101.com/r/AUDili/1

  •  Tags:  
  • Related