Search code examples
regexemacsalignmenttext-alignment

In emacs, can I use alternation in the regexp for align-regexp?


For example, I have the following snippet:

'abc' => 1,  
'abcabc' =>2,  
'abcabcabc' => 3,

And I want to format it to:

'abc'       => 1,  
'abcabc'    => 2,  
'abcabcabc' => 3,  

I know there are easier ways to do it but here I'm just want to practice my understanding of align-regexp. I've tried this command but it does not work:

C-u M-x align-regexp \(\s-+\)=\|\(>\s-*\)\d 1 1 y

Where I'm wrong? Thanks.


Solution

  • So the question is: With \(\s-+\)=\|\(>\s-*\)\d matching \(\s-+\)= or \(>\s-*\)\d1, can we use align-regexp to align on each of those alternatives throughout a line.

    The answer is no -- align-regexp modifies one specific matched group of the regexp. In this case it was group 1, and group 1 is the \(\s-+\) at the beginning. Group 1 of the regexp does not vary depending on what was actually matched, and so it never refers to \(>\s-*\)2.

    If you can express your regexp such that it really is a single group of the regexp which should be replaced for every match throughout the line, you can get the effect you want, however.

    e.g. >?\(\s-*\)[0-9=] would -- at least for the data shown -- give the desired result.

    1 In Emacs \d matches d. That should be [0-9].
    2 You generally don't want any non-whitespace in the alignment group, as Emacs replaces the content of that group.