With M-x replace-regexp
, I found that both \([[:digit:]]+\)
and ([[:digit:]]+)
will match (123)
, and not one without parentheses, But the first will replace 123
and the second (123)
. I wonder why the difference?
1 Answer
In emacs regular expressions (unlike most regexp engines), \(
and \)
are group delimiters, while (
and )
match litteral brackets.
So: \([[:digit:]]+\)
matches one digit or more, that is here 123
, and makes it a group. That means that for example, \([[:digit:]]+\)?
would match either 123
or some empty string, and that you can use \1
(assuming it is your only group) for 123
in the replacement text.
On the other hand, ([[:digit:]]+)
matches an opening bracket, one digit or more, then a closing bracket, so it will match (123)
.
-
Is emacs the only one that uses this convention? Or does it follow some standard which also applies to other engines?– TimCommented Oct 10, 2014 at 14:19
-
For example,
sed
does use a similar convention by default, but it doesn't force you to use this implementation (you can choose the regexp style that you prefer through command line flags). With emacs, you have no built-in alternative. Commented Oct 10, 2014 at 14:26 -
-
No. POSIX regexes use unescaped brackets as group delimiters, escaped brackets are litteral brackets. The behavior of braces and escaped braces is similarly swapped. Commented Oct 10, 2014 at 14:30
-
\([[:digit:]]+\)
should definitely match123
. Doesn't it for you?\([[:digit:]]+\)
matches any number of digits. So it matches123
and it also matches the numbers in(123)
. In both cases it replaces only the numbers.