[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Regular expressions and user-escaped characters
From: |
Stefan Monnier |
Subject: |
Re: Regular expressions and user-escaped characters |
Date: |
Tue, 03 Dec 2024 09:01:01 -0500 |
User-agent: |
Gnus/5.13 (Gnus v5.13) |
> Hi, what do you do in a regular expression if you want to match a character,
> but not a the same character that has been escaped by the user. E.g., if
> I want my regular expression to look for ?\[ (ASCII 91), matching string "["
> and "a[a" but not string "\\[" or "a\\[a", if you follow me. Is this
> possible with just a regular expression?
The "usual" way we do that is with the godawful:
"\\(?:^\\|[^\\]\\(?:\\\\\\\\\\)*\\)\\["
This is careful to match the [ if it's preceded by an even number
of backslashes. But beware that it makes more than the actual [, so if
you start the search from a point that's looking at a [, it won't find
it (except if it's at the beginning of the line).
> If not, what is a good workaround?
Just use a regexp which matches all [ (regardless of any previous
backslashes) and then check afterwards, in ELisp, whether it's preceded
by an odd number of backslashes, e.g. with something like
(save-excursion
(goto-char <FOO>)
(zerop (% (skip-chars-backward "\\") 2)))
- Stefan