Monkless has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I once again come seeking your wisdom -- I have an array of regex patterns that I would like to match on but my current code block seems to only match once and stop, but the string has most matches within it...

my $devicesData = '"deviceId": 6931162, "friendlyName": "U12H240T70 - R6300v2", "lastInform": "2016-02-15T15:08:24.611Z", "sn": "4401487KA0276", "subscriberCode": "8245112910034496"'; my @matches = ( qr/"sn": "(.+?)"/, qr/"subscriberCode": "(.+?)"/, qr/"friendlyName": "(.+?)"/, qr/"SolicitTimestamp": "(.+?)"/, qr/"StatusCode": "(.+?)"/, ); if ($devicesData ~~ @matches) { print "Found: $1\n"; } #output Found: 4401487KA0276

With this method, is it possible to match on each pattern? I feel like I'm missing a regex operator to continue to check matches - I tried using the g modifier and join | to each element but to no avail -- Additionally, I went this route vs having 5 separate regex calls with each pattern so that if this scripts needs to grow, I can simply add the pattern to the match array and be flexible as the data could change at some point! Always, greatly appreciate the direction!

Replies are listed 'Best First'.
Re: Regex Array matching
by poj (Abbot) on Feb 15, 2016 at 21:25 UTC

    Why use a regex ?

    #!perl use strict; use JSON; my $devicesData = '"deviceId": 6931162, "friendlyName": "U12H240T70 - R6300v2", "lastInform": "2016-02-15T15:08:24.611Z", "sn": "4401487KA0276", "subscriberCode": "8245112910034496"'; my $hr = decode_json "{$devicesData}"; print "$_ = $hr->{$_}\n" for keys %$hr;
    poj

      Thanks poj - Seems I was over thinking this and making it more difficult than need be - Your suggestion seems to be a viable solution! Thanks Again!!

Re: Regex Array matching
by mr_ron (Deacon) on Feb 15, 2016 at 21:59 UTC

    The code:

    print "Found: $_\n" foreach map { $devicesData =~ $_ } @matches;

    would seem to print what you "said" you wanted. The solution from poj may be more broadly useful.

    Ron

      Thanks Ron! This indeed was what I was looking for initially.. good looking out, I can see this being useful as well