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?Tim– Tim2014-10-10 14:19:08 +00:00Commented Oct 10, 2014 at 14:19
- For example,
seddoes 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.T. Verron– T. Verron2014-10-10 14:26:37 +00:00Commented Oct 10, 2014 at 14:26 - Does emacs regex follow POSIX standard?Tim– Tim2014-10-10 14:27:51 +00:00Commented Oct 10, 2014 at 14:27
- No. POSIX regexes use unescaped brackets as group delimiters, escaped brackets are litteral brackets. The behavior of braces and escaped braces is similarly swapped.T. Verron– T. Verron2014-10-10 14:30:16 +00:00Commented Oct 10, 2014 at 14:30
- by brackets [], you wanted to mean (), right?Tim– Tim2014-10-10 15:34:28 +00:00Commented Oct 10, 2014 at 15:34
\([[:digit:]]+\)should definitely match123. Doesn't it for you?\([[:digit:]]+\)matches any number of digits. So it matches123and it also matches the numbers in(123). In both cases it replaces only the numbers.