Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How do I replace part of a pattern and reference a variable within it?

Tags:

regex

replace

vi

I want to match a pattern, replace part of the pattern, and use a variable within the pattern as part of the replacement string.

Is this correct?

/s/^((\s+)private\sfunction\s__construct\(\))/(2)def\s__init__

In English: Replace any amount of whitespace followed by the string "private function __construct()" with the same amount of whitespace and the string def __init__. So, is my regex bad or what?

partial replace

like image 658
Wolfpack'08 Avatar asked Jan 18 '12 01:01

Wolfpack'08


2 Answers

I presume you want to replace it in vi

Replace all occurrences

:s/^\(\s\+\)private function __construct()/\1def __init__/g

Replace first

:s/^\(\s\+\)private function __construct()/\1def __init__/

Few suggestions to your pattern

  • / is used in vi for search , use :
  • you need to escape ( ) in vi
  • use \i where i is xth capture group like \1 \2 to back reference grouped patterns in replacement
  • \s can not be used in replacement text use ' ' instead
  • use trailing /g if you want to replace all occurrences

http://vimregex.com should help you get started.

like image 106
Prashant Bhate Avatar answered Oct 17 '22 02:10

Prashant Bhate


This is called a backreference, and you use \i to refer to the i'th captured group from the pattern.

So for the pattern ^((\s+)private\sfunction\s__construct\(\)), the replacement is \2def __init__.

like image 24
mathematical.coffee Avatar answered Oct 17 '22 02:10

mathematical.coffee