正则表达式:如何替换模式的一部分并引用其中的变量?
我想匹配一个模式,替换部分模式,并使用模式中的变量作为替换字符串的一部分。
这是正确的吗?
/s/^((\s+)private\sfunction\s__construct\(\))/(2)def\s__init__
英语:替换任意数量的空格,后跟字符串 "private function __construct()"
具有相同数量的空格和字符串 def __init__
。那么,是我的正则表达式不好还是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您想在
vi
中替换它替换所有出现的情况
替换第一个
对您的模式的一些建议
/
在vi
中用于搜索,请使用 < code>:(
)
\i
其中 i 是第 x 个捕获组,如\ 1
\2
返回引用分组模式替换\s
不能在替换文本中使用,' '
而不是使用尾随/g
http://vimregex.com 应该可以帮助您入门。
I presume you want to replace it in
vi
Replace all occurrences
Replace first
Few suggestions to your pattern
/
is used invi
for search , use:
(
)
in vi\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/g
if you want to replace all occurrenceshttp://vimregex.com should help you get started.
这称为反向引用,您使用
\i
来引用模式中第 i 个捕获的组。因此,对于模式
^((\s+)private\sfunction\s__construct\(\))
,替换为\2def __init__
。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__
.我认为没有人真正理解这个问题。基本上,我这样做的方式如下:
“如果您想搜索替换模式模式 a,并将其替换为替换字符串模式 i,仅当它以模式模式 b 开头时,然后您需要在替换字符串中包含模式 b,如下所示::/(模式 b)(模式 a)/(模式 b)(i)/g"。
虽然有点啰嗦,但值得一读。
过去,我确信有人会想,“实际上不用
pattern b
替换pattern b
可以节省大量资源。这样做是多余的”。也许它会自动发生。我还没有在 vi 或任何其他程序中找到内置方法来执行此操作。不过,我确信我可以编写一个脚本来做到这一点。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
withpattern 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.