使用变量作为正则表达式替换参数
我一直在进行一些搜索,但没有找到答案。为什么这不起作用?
$self->{W_CONTENT} =~ /$regex/;
print $1; #is there a value? YES
$store{URL} =~ s/$param/$1/;
是的,1 美元有价值。 $param 被替换,但它什么也没替换。我确信 1 美元有价值。如果我用文本替换而不是“$1”,它就可以正常工作。请帮忙!
I've been doing some searching and haven't found an answer. Why isn't this working?
$self->{W_CONTENT} =~ /$regex/;
print $1; #is there a value? YES
$store{URL} =~ s/$param/$1/;
Yes $1 has a value. $param is replaced however it is replaced with nothing. I'm positive $1 has a value. If I replace with text instead of "$1" it works fine. Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要使
$1
具有值,您需要确保$param
中包含括号()
。即以下问题与您所解释的类似。但这是可行的
。现在,如果您想在第二个正则表达式中使用第一个正则表达式中的
$1
,则需要复制它。每个正则表达式评估都会重置$1
...$&
。所以你想要这样的东西:For
$1
to have a value you need to ensure that$param
has parentheses()
in it. i.e. The following has a problem similar to what you are explaining.But this works
Now if you want to use the
$1
from your first regex in the second one you need to copy it. Every regex evaluation resets$1
...$&
. So you want something like:表达式内部不应使用诸如 $1 之类的反向引用;您可以使用不同的表示法 - 有关概述,请查看 Perl 正则表达式快速入门。
考虑获取 $1 的值并将其存储在另一个变量中,然后在正则表达式中使用该变量。
Backreferences such as $1 shouldn't be used inside the expression; you'd use a different notation - for an overview, check out Perl Regular Expressions Quickstart.
Consider getting the value of $1 and storing it in another variable, then using that in the regex.