阅读背景:

如何使用perl正则表达式从“[1]”中提取数字值?

来源:互联网 

My code...

$option = "[1]";
if ($option =~ m/^\[\d\]$/) {print "Activated!"; $str=

My code...

$option = "[1]";
if ($option =~ m/^\[\d\]$/) {print "Activated!"; $str=$1;}

I need a way to drop off the square brackets from $option. $str = $1 does not work for some reason. Please advise.

我需要一种方法从$ option中删除方括号。 $ str = $ 1由于某种原因不起作用。请指教。

2 个解决方案

#1


6  

if ($option =~ m/^\[(\d)\]$/) { print "Activated!"; $str=$1; }

Or

if (my ($str) = $option =~ m/^\[(\d)\]$/) { print "Activated!" }

Or

if (my ($str) = $option =~ /(\d)/) { print "Activated!" }

..and a bunch of others. You forgot to capture your match with ()'s.

..和其他一些人。你忘了用()来捕捉你的比赛。

EDIT:

if ($option =~ /(?<=^\[)\d(?=\]$)/p && (my $str = ${^MATCH})) { print "Activated!" }

Or

my $str;
if ($option =~ /^\[(\d)(?{$str = $^N})\]$/) { print "Activated!" }

Or

if ($option =~ /^\[(\d)\]$/ && ($str = $+)) { print "Activated!" }

For ${^MATCH}, $^N, and $+, perlvar.

对于$ {^ MATCH},$ ^ N和$ +,perlvar。

I love these questions : )

我喜欢这些问题:)

#2


7  

To get $1 to work you need to capture the value inside the brackets using parentheses, i.e:

要获得1美元的工作,您需要使用括号捕获括号内的值,即:

if ($option =~ m/^\[(\d)\]$/) {print "Activated!"; $str=$1;}

;} $option = "[1]"; if ($option =~ m/



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: