Previous Next
Groups, alternatives and back references

Groups -- enclosed in \parentheses -- \(...\)
Alternatives -- \pipe -- \|
Back references -- \1...\9

Groups enclosed in \(...\) serve three purposes

Examples
  1. This example matches
    SetupMenu or SetupStyles and
    changes
    Setup to Update
    concatenates this with
    Menu or Styles (whichever was matched) and
    adds the substring
    Always at the end.

    Find:
    Setup\(Menu\|Styles\)
    Change to:
    Update\1Always

    Good results
    Found
    Do SetupMenu and changed to Do UpdateMenuAlways
    Found SetupStyles and changed to UpdateStylesAlways

    Potential pitfall
    Found SetupMenu
    Styles and changed to UpdateMenuAlways Styles
    Remember: "The first match always wins."

  2. This example matches foo(parameter1,parameter2) and changes the parameter order. Nonprinting characters are not taken into account, nor are nested parentheses considered.

    Find:
    <foo(\([^,]+\), \([^,]+\)
    Change to:
    foo(\2,\1)

    Good results
    Found foo(a,b) and changed to foo(b,a)
    Found foo(int a,char* b) and changed to foo(char* b,int a)

    Potential pitfall
    Found foo(f(x,y)
    ,int b) and changed to foo(y),f(x ,int b)
    You could of course "fix" the regex by matching ';' at the end, but that does not solve the actual problem. As always, it's safer to check before globally changing things.
    Regular expressions are cumbersome for nested parentheses of any depth, and cannot handle arbitrary depths.