正则表达式:如何替换模式的一部分并引用其中的变量? [英] Regex: How do I replace part of a pattern and reference a variable within it?
问题描述
我想匹配一个模式,替换部分模式,并使用模式中的一个变量作为替换字符串的一部分.
I want to match a pattern, replace part of the pattern, and use a variable within the pattern as part of the replacement string.
这是正确的吗?
/s/^((\s+)private\sfunction\s__construct\(\))/(2)def\s__init__
英语:用相同数量的空格和字符串 def __init__
替换任意数量的空格后跟字符串 "private function __construct()"
.那么,是我的正则表达式不好还是什么?
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?
推荐答案
这称为反向引用,您可以使用 \i
来引用模式中第 i 个捕获的组.
This is called a backreference, and you use \i
to refer to the i'th captured group from the pattern.
>
所以对于模式^((\s+)private\sfunction\s__construct\(\))
,替换为\2def __init__
.
这篇关于正则表达式:如何替换模式的一部分并引用其中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!