Regex: How do I replace part of a pattern and refe

2019-03-19 20:12发布

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

标签: regex vi replace
3条回答
小情绪 Triste *
2楼-- · 2019-03-19 20:27

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.

查看更多
萌系小妹纸
3楼-- · 2019-03-19 20:33

I don't think anyone really understood the question. Basically, the way I'm doing this is as follows:

"If you want to search for a replacement pattern, pattern a, and replace it with a replacement string, pattern i, only if it starts with a pattern, pattern b, then you need to include pattern b in the replacement string, like this: :/(pattern b)(pattern a)/(pattern b)(i)/g".

It's a little wordy but worth reading.

In the past, I'm sure that someone has thought, "It could save a lot of resources to not actually replace pattern b with pattern b. It's redundant to do so." Maybe it happens automatically. I haven't found a built-in method in vi or any other program to do that. I'm sure I could write a script to do it, though.

查看更多
放荡不羁爱自由
4楼-- · 2019-03-19 20:36

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

查看更多
登录 后发表回答