Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to escape the parentheses

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?

like image 776
RoundOutTooSoon Avatar asked Apr 26 '12 03:04

RoundOutTooSoon


People also ask

How do you match parentheses in regex?

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.

What does '$' mean in regex?

$ 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.

Do I need to escape brackets in regex?

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 "]".

What is the difference between () and [] in regex?

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.


1 Answers

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\(.+\)
like image 101
alan Avatar answered Sep 28 '22 10:09

alan