Match regex and assign results in single line of code

后端 未结 9 1917
后悔当初
后悔当初 2021-02-02 06:45

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?

I want to essentially combine lines 2 a

相关标签:
9条回答
  • 2021-02-02 07:05

    Also, to amplify the accepted answer using the ternary operator to allow you to specify a default if there is no match:

    my $match = $variable =~ /(*pattern*).*/ ? $1 : *defaultValue*;
    
    0 讨论(0)
  • 2021-02-02 07:19
    my($variable) = "some string" =~ /(e\s*str)/;
    

    This works because

    If the /g option is not used, m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3 …).

    and because my($variable) = ... (note the parentheses around the scalar) supplies list context to the match.

    If the pattern fails to match, $variable gets the undefined value.

    0 讨论(0)
  • 2021-02-02 07:22

    You can do substitution as:

    $a = 'stackoverflow';
    $a =~ s/(\w+)overflow/$1/;
    

    $a is now "stack"

    0 讨论(0)
  • 2021-02-02 07:22
    $variable2 = "stackoverflow";
    (my $variable1) = ($variable2 =~ /stack(\w+)/);
    

    $variable1 now equals "overflow".

    0 讨论(0)
  • 2021-02-02 07:23

    Almost ....

    You can combine the match and retrieve the matched value with a substitution.

    $variable =~ s/.*(find something).*/$1/;
    

    AFAIK, You will always have to copy the value though, unless you do not care to clobber the original.

    0 讨论(0)
  • 2021-02-02 07:26

    I do this:

    #!/usr/bin/perl
    
    $target = "n: 123";
    my ($target) = $target =~ /n:\s*(\d+)/g;
    print $target; # the var $target now is "123"
    
    0 讨论(0)
提交回复
热议问题