Grouping in regular expressions in javascript

Go To StackoverFlow.com

1

i want to match all the text in both "" and ''. My text may contain any of these so i used or operator My regular expression is as follows

(\"(.*?)\"|'(.*?)')

to retrieve the text between quotes i have used groups like RegExp.$2 for "" and RegExp.$3 for '' Now using only one group can i retrieve either of these. For example i might not be knowing when "" is given and '' is used so can any one suggest a regular expression which satisfies the above mentioned property.

2012-04-04 06:52
by user1275375


3

Try this

(['"])(.*?)\1

See it here on Regexr

You will find the text between quotes inside group 2.

2012-04-04 07:02
by stema


1

Something like this?

(["'])((?:(?!\1).)*)\1

First backreference will contain " or ' while the second one will contain the text between quotes.

And if this is code you want to match (strings between quotes), you may want to handle backslashes:

(["'])((?:(?!\1)[^\\]|\\.)*)\1
2012-04-04 06:58
by Etienne Perot
I dont understand , his code is working - Royi Namir 2012-04-04 07:00
Yes, but I think he is complaining that he has to check two backreferences instead of one, and wants to merge them into one to make the logic simpler (question says "using only one group can i retrieve either of these"). At least that's how I interpreted the questio - Etienne Perot 2012-04-04 07:01
oh ok.......... - Royi Namir 2012-04-04 07:02
You can't use a back reference in a character class. Your regex is not working as you may expect - stema 2012-04-04 07:04
My bad, indeed. Fixed both regexe - Etienne Perot 2012-04-04 07:07
Thats better now. IMO using the lookahead is here a bit complicated but a valid solution - stema 2012-04-04 07:15
Ads