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

后端 未结 3 563
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题