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

后端 未结 3 557
借酒劲吻你
借酒劲吻你 2021-02-08 20:25

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

相关标签:
3条回答
  • 2021-02-08 20:54

    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.

    0 讨论(0)
  • 2021-02-08 20:57

    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.

    0 讨论(0)
  • 2021-02-08 21:01

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

    0 讨论(0)
提交回复
热议问题