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.

2 Answers 2

3

Try this

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

See it here on Regexr

You will find the text between quotes inside group 2.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

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 question
You can't use a back reference in a character class. Your regex is not working as you may expect.
My bad, indeed. Fixed both regexes
Thats better now. IMO using the lookahead is here a bit complicated but a valid solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.