How to use perl regex to extract the value of a digit from "[1]"?

My code ...

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

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

+4
source share
2 answers
 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 many others. You forgot to fix your match with () .

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 like these questions :)

+6
source

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

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

Source: https://habr.com/ru/post/1332704/


All Articles