I tried different ways to escape the parentheses using regex in JavaScript but I still can't make it work.
This is the string:
"abc(blah (blah) blah()...).def(blah() (blah).. () ...)"
I want this to be detected:
abc().def()
Using this code, it returns false.
str.match(/abc\([^)]*\)\.def\([^)]*\)/i);
Can you please tell me why my regex is not working?
The way we solve this problem—i.e., the way we match a literal open parenthesis '(' or close parenthesis ')' using a regular expression—is to put backslash-open parenthesis '\(' or backslash-close parenthesis '\)' in the RE. This is another example of an escape sequence.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Opening and closing brackets must be escaped when used inside a character class "[\\[\\]]", but not when used outside character class. Regex. Escape doesn't escape "]".
In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.
This regex will match the string you provided:
(abc\().+(\)\.def\().+(\))
And using backreferences $1$2$3
will produce abc().def()
Or just use this if you don't want the back references:
abc\(.+\)\.def\(.+\)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With