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...
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.
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.
$hash{$1} = $2 while
$text =~ /\{IS\:([a-zA-Z0-9_-]+)\}
(.*)
\{\\IS\:([a-zA-Z0-9_-]+)\}/gx;
(/x
modifier added for readability)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With