简体   繁体   中英

How do I use perl regex to extract the digit value from '[1]'?

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.

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

if ($option =~ m/^\[(\d)\]$/) {print "Activated!"; $str=$1;}
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 .

I love these questions : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM