6

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?

3
  • \([[:digit:]]+\) should definitely match 123. Doesn't it for you?
    – Malabarba
    Commented Oct 10, 2014 at 20:00
  • seems match (123) not 123, but replace 123 inside (123). or am i wrong?
    – Tim
    Commented Oct 10, 2014 at 20:18
  • \([[:digit:]]+\) matches any number of digits. So it matches 123 and it also matches the numbers in (123). In both cases it replaces only the numbers.
    – Malabarba
    Commented Oct 10, 2014 at 20:35

1 Answer 1

11

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).

enter image description here

enter image description here

9
  • Is emacs the only one that uses this convention? Or does it follow some standard which also applies to other engines?
    – Tim
    Commented 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.
    – T. Verron
    Commented Oct 10, 2014 at 14:26
  • Does emacs regex follow POSIX standard?
    – Tim
    Commented 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
    Commented Oct 10, 2014 at 14:30
  • by brackets [], you wanted to mean (), right?
    – Tim
    Commented Oct 10, 2014 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.