Can you use back references in the pattern part of a regular expression?

Posted by Camsoft on Stack Overflow See other posts from Stack Overflow or by Camsoft
Published on 2010-04-27T15:21:32Z Indexed on 2010/04/27 15:23 UTC
Read the original article Hit count: 319

Filed under:
|
|

I there a way to back reference in the regular expression pattern?

Example input string:

Here is "quoted text" some quoted text.

Say I want to pull out the quoted text, I could create the following expression:

"([^"]+)"

This regular expression would match quoted text.

Say I want it to also support single quotes, I could change the expression to:

["']([^"']+)["']

But what if the input string has a mixture of quotes say Here is 'quoted text" some quoted text. I would not want the regex to match. Currently the regex in the second example would still match.

What I would like to be able to do is if the first quote is a double quote then the closing quote must be a double. And if the start quote is single quote then the closing quote must be single.

Can I use a back reference to achieve this?

© Stack Overflow or respective owner

Related posts about regular-expressions

Related posts about regex