匹配正则表达式并在单行代码中分配结果 [英] Match regex and assign results in single line of code
问题描述
我希望能够对变量进行正则表达式匹配并将结果分配给变量本身.最好的方法是什么?
I want to be able to do a regex match on a variable and assign the results to the variable itself. What is the best way to do it?
我想在一行代码中基本上合并第 2 行和第 3 行:
I want to essentially combine lines 2 and 3 in a single line of code:
$variable = "some string";
$variable =~ /(find something).*/;
$variable = $1;
有没有更短/更简单的方法来做到这一点?我错过了什么吗?
Is there a shorter/simpler way to do this? Am I missing something?
推荐答案
你为什么希望它更短?真的重要吗?
Why do you want it to be shorter? Does is really matter?
$variable = $1 if $variable =~ /(find something).*/;
如果你担心变量名或者重复做这个,把东西包在一个子程序里,不管它:
If you are worried about the variable name or doing this repeatedly, wrap the thing in a subroutine and forget about it:
some_sub( $variable, qr/pattern/ );
sub some_sub { $_[0] = $1 if eval { $_[0] =~ m/$_[1]/ }; $1 };
无论您如何实现它,子例程的重点是使其可重用,因此您可以为一组特定的行指定一个简短的名称来代替它们.
However you implement it, the point of the subroutine is to make it reuseable so you give a particular set of lines a short name that stands in their place.
其他几个答案提到了破坏性替代:
Several other answers mention a destructive substitution:
( my $new = $variable ) =~ s/pattern/replacement/;
我倾向于保留原始数据,并且 Perl v5.14 有一个 /r
标志,它不影响原始文件并返回一个带有替换的新字符串(而不是替换的计数)):
I tend to keep the original data around, and Perl v5.14 has an /r
flag that leaves the original alone and returns a new string with the replacement (instead of the count of replacements):
my $match = $variable =~ s/pattern/replacement/r;
这篇关于匹配正则表达式并在单行代码中分配结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!