I have a string like this:
a b c a b ” a b ” b a ” a “
How do I match every a that is not part of a string delimited by "? I want to match everything that is bold here:
a bc a b ” ab ” b a ” a “
I want to replace those matches (or rather remove them by replacing them with an empty string), so removing the quoted parts for matching won’t work, because I want those to remain in the string. I’m using Ruby.
Assuming the quotes are correctly balanced and there are no escaped quotes, then it’s easy:
This replaces all the
as with the empty string if and only if there is an even number of quotes ahead of the matcheda.Explanation:
If you can have escaped quotes within quotes (
a "length: 2\""), it’s still possible but will be more complicated:This is in essence the same regex as above, only substituting
(?:\\.|[^"\\])for[^"]: