Using RegExp to match parentheses with a given number of characters inside
I am trying to write a regex that will match the parentheses (555)
in 1 (555) 555-5555
and replace the parentheses with nothing. However, there should be no matches if there is only one parenthesis, such as in this case, 1 555)555-5555
or if there are more than three numbers / characters in the parentheses, such as in (6505552368)
.
My best attempt is
re = /\((?=.{3})/;
But it will only match the first parenthesis and replace it, which doesn't help much. Would feel any ideas.
source to share
If you need to remove the first parentheses around 3 digits in a string, you can use
s.replace(/\((\d{3})\)/, '$1')
See regex demo
More details
-
\(
- symbolic character(
-
(\d{3})
- Group 1 (later referred to with$1
backreference) -
\)
- literal)
-
$1
- link to group 1.
Or, if you only need to remove two parentheses that appear after zero or more digits / spaces, use
s.replace(/^([\d\s]*)\((\d{3})\)/, '$1$2')
See another regex demo .
More details
-
^
- beginning of line -
([\d\s]*)
- Group 1 (hereinafter called$1
): 0 + numbers and / and spaces -
\(
- a(
char -
(\d{3})
- Group 2 capturing 3 digits -
\)
- literal)
Here, $1$2
to recover the texts is out (
and )
requires two backlinks.
source to share
Not sure if this is the best regex, but it will work.
Regex: (?: ^ | () (\ D {3}) (? :) | $)
For demonstration purposes, I replaced ()
with _
.
var regex = /(?:^|\()(\d{3})(?:\)|$)/g;
var str = "1 (555) 555-5555 (1234), or (123 or 123)";
console.log(str.replace(regex, "_$1_"))
In my understanding, @ Wiktor's answer is better. However, I am keeping my answer as a reference.
source to share
I modified Rajesh's solution a bit, so each parenthesis will be replaced with nothing.
var patt = /\((\d{0,3})\)/g;
var str = '55 (555) 555-(55)55';
console.log(str.replace(patt, "$1"));
But that doesn't solve it if you need to replace even nested parentheses. For that you can use this code:
var patt = /\((\d{0,3})\)/g;
var str = '55 (5(5)(((5)))) 555-(55)55';
while(str.match(/\((\d{0,3})\)/g))
{
str = str.replace(patt, "$1");
}
console.log(str);
Hope this helps.
source to share