Home > other >  Perl regex to extract multiple matches from string
Perl regex to extract multiple matches from string

Time:12-10

I have a string for example "id:123,createdby:'testuser1',"lastmodifiedby":'testuser2'....". I want to extract the 2 user names (testuser1, testuser2) and save it to an array.

CodePudding user response:

Try this

use strict;
use warnings;

my $string = q[id:123,createdby:'testuser1',"lastmodifiedby":'testuser2'....];

my @matches = ($string =~ /,createdby:'(. ?)',"lastmodifiedby":'(. ?)'/) ;

print " @matches\n";

Outputs

testuser1 testuser2

User requirements changed to allow coping with missing files. To deal with that, try this

use strict;
use warnings;

my $string1 = q[id:123,createdby:'testuser1',"lastmodifiedby":'testuser2'....];
my $string2 = q[id:123,createdby:'testuser1'....] ;

for my $s ($string1, $string2)
{
    my @matches = ( $s =~ /(?:createdby|"lastmodifiedby"):'(. ?)'/g ) ;
    print "@matches\n";
}

Outputs

testuser1 testuser2
testuser1
  • Related