Paul T Paul T - 2 months ago 7
Perl Question

How to create $var from $str with regexp using Perl

I have

$str = "dfsdfsdfsd fdsdfs ifdasda id=322dasd-ewwedasda"


and wrote a regex

\id\=\w.+


I need to get the result

$string = "id=322dasd-ewwedasda"

Answer
my $str = 'dfsdfsdfsd fdsdfs ifdasda id=322dasd-ewwedasda';
my ($string) = $str =~ /\b(id=\w.+)/;

$string will be undef if there's no match. You can also die if there's no match using the following:

my ($string) = $str =~ /\b(id=\w.+)/
    or die("No match!");

Though \w.+ is a very strange pattern to use. Perhaps you wanted \w+?