Reputation: 1208
It actually does work.
I am trying to use Regex to match strings with one character surrounded by single quotes '
where both quotes cannot be preceded by a backslash \
.
This is my Regex:
(?<!\\)'(.{1})(?<!\\)'
It uses negative lookbehind to ensure that the quotes are not preceded by a backslash.
So far, it works great, but I've run into a certain problem:
From 'H'ello world!
it matches 'H'
, and from \'H'ello world
it doen't match 'H'
because the 'H'
is preceded by \
.
The problem I run into is that if I have this string:
'I' have \'r'eally bad 'e'xamples
it will match 'I'
because it is not preceded by \
, it won't match \'r'
because it is preceded by \
, but it won't match 'e'
because it is not directly preceded by \
but there is an occurrence of \
before that (before 'r'
).
So my question is, is there any way to specify a "maximum distance" that the negative lookbehind should look for the \
?
Thanks in advance!
Upvotes: 2
Views: 491
Reputation: 425348
Firstly, your look behind is not variable length; it has length exactly 1, because it has only one character.
Secondly, you only need one look behind; the second one is not needed if the dot doesn't match a backslash.
Your regex can be simplified to:
(?<!\\)'[^\\]'
Upvotes: 1