Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map regex string replacement values ($1,$2 etc) to a hash?

Tags:

regex

hash

map

perl

my (@keys,@values) = ($text =~ /\{IS\:([a-zA-Z0-9_-]+)\}(.*)\{\\IS\:([a-zA-Z0-9_-]+)\}/g);

is supposed to match strings like this

{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}    
{IS:dog}bark{\IS:dog}
{IS:dog}meow{\IS:dog} #probably not a dog

which works fine, except that all the $1,$2, and $3 value get dumped into @keys .. so I'm trying to figure out how to get these guys into a nice hash of $1 => $2 pairs...

For full context what I'd really like to do however is have the regex expression return a data structure that looks like (and append a count for the number of times the key was found)

{ 
  cow_1 => moo,
  cow_2 => moo,
  dog_1 => bark,
  dog_2 => meow,
}

Is there a way to use map{ } function to accomplish this with Regex? Something like this maybe?

my %datahash = map { ( $1 eq $3 ) ? { $1 => $2 } : undef } @{ regex...};

$1 equals $3 to make sure its a matching tag (no need for recursive checking these tags aren't nested), if so use $1 as the key and $2 as the value;

Then for each of these key => value pairs, i want to replace

{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}   

with

{cow_1}
{cow_2}

then if $cachedData{cow} is true all cow_* will be replaced with their key in %datahash...

like image 652
qodeninja Avatar asked Nov 29 '11 21:11

qodeninja


People also ask

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Can regex replace characters?

RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.

Can we use regex in replace Java?

When we need to find or replace values in a string in Java, we usually use regular expressions. These allow us to determine if some or all of a string matches a pattern. We might easily apply the same replacement to multiple tokens in a string with the replaceAll method in both Matcher and String.


1 Answers

$hash{$1} = $2 while 
        $text =~ /\{IS\:([a-zA-Z0-9_-]+)\}
                           (.*)
                  \{\\IS\:([a-zA-Z0-9_-]+)\}/gx;

(/x modifier added for readability)

like image 185
mob Avatar answered Oct 05 '22 07:10

mob