Reputation: 2824
I'm trying to write a regex to match single quotes, which may be escaped. A matched quote should have an even number of backslashes before it (an odd number means that the quote is escaped). For example, in these five strings:
'quotes should be matched'
\'quotes should NOT be matched\'
\\'quotes should be matched\\'
\\\'quotes should NOT be matched\\\'
\\\\'quotes should be matched\\\\'
Here is the regex that I have:
(?<=[^\\](?:\\\\)*)'
However, this does not match anything in the above example. I find this strange because removing the *
from the regex matches the quotes with two backslashes, as it should:
(?<=[^\\](?:\\\\))'
matches \\'
Upvotes: 1
Views: 145
Reputation: 1559
As far as I can see, it's not possible to match just the '
. This is because you can't have dynamic length lookbehinds as Wiseguy pointed out.
The following regex would match the correct '
AND any \
s leading up to it however. Not sure if this will be of any use..
(?<!\\)(?:\\\\)*'
Matches an arbitrary number of double \
s not preceded by a \
and followed by a '
.
Upvotes: 3