RoundOutTooSoon
RoundOutTooSoon

Reputation: 9891

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?

Upvotes: 14

Views: 43783

Answers (2)

LearningDeveloper
LearningDeveloper

Reputation: 658

K... Here's an Idea...

abc(blah (blah) blah()).def(blah() (blah).blah())

Use regExp like this

var regExp1 = \^([a-z])*\(\ig;

it'll match

abc(

then use

var regExp2 = /\)\./

it'll match the

")." 

in the string..

then split the actual string so that it becomes

def(blah() (blah).blah())

repeat till the regular expression can't find the

regExp2 

and add a closing bracket.. The simplest solution I could think of.. Hope it helps..

Upvotes: 0

alan
alan

Reputation: 4842

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\(.+\)

Upvotes: 12

Related Questions