Rafael
Rafael

Reputation: 1223

Regex for text inside double quotes

I'm trying to match these strings:

" ... " Text inside double quotes

' ... ' Text inside single quotes

" ' " There can be apostrophes inside

" \" " There can be escaped double quotes

But not these:

' " ' Not double quotes inside single quotes

" " " Not double quotes inside double quotes

''' Single quotes inside single quotes - Single quotes can only contain text inside

I have came up with the following regex:

['"](?(["])[^\"-"][\w])['"]

But it's not working.

Upvotes: 0

Views: 383

Answers (2)

Mike H-R
Mike H-R

Reputation: 7815

You could use something like this:

"(?:[^"\\]|\\.)*?"|'(?:[^\\"']|\\.)*?'

I've followed what you've put but I wonder about it (Why no double quotes inside single quotes? I have not allowed a single quote inside single quotes though you've said nothing about that).

Either way, here is an example

Upvotes: 1

Qtax
Qtax

Reputation: 33908

Usually to match quotes with escapes as in C styled languages (and with single quoting as in JS) you could use:

"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'

Upvotes: 4

Related Questions