qod*_*nja 5 regex perl hash map
my (@keys,@values) = ($text =~ /\{IS\:([a-zA-Z0-9_-]+)\}(.*)\{\\IS\:([a-zA-Z0-9_-]+)\}/g);
Run Code Online (Sandbox Code Playgroud)
应该匹配这样的字符串
{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}
{IS:dog}bark{\IS:dog}
{IS:dog}meow{\IS:dog} #probably not a dog
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,除了所有的$ 1,$ 2和$ 3值被转储到@keys ..所以我想弄清楚如何让这些家伙成为$ 1 => $ 2对的漂亮哈希......
对于完整的上下文,我真正想做的是让regex表达式返回一个看起来像的数据结构(并附加一个计数,找到键的次数)
{
cow_1 => moo,
cow_2 => moo,
dog_1 => bark,
dog_2 => meow,
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用map {}函数来完成Regex?这样的事可能吗?
my %datahash = map { ( $1 eq $3 ) ? { $1 => $2 } : undef } @{ regex...};
Run Code Online (Sandbox Code Playgroud)
$ 1等于$ 3以确保其匹配标记(不需要递归检查这些标记不嵌套),如果是这样,则使用$ 1作为键,$ 2作为值;
然后,对于这些key =>值对中的每一个,我想要替换
{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}
Run Code Online (Sandbox Code Playgroud)
同
{cow_1}
{cow_2}
Run Code Online (Sandbox Code Playgroud)
然后,如果$ cachedData {cow}为true,则所有cow_*将替换为%datahash中的键...
我从正则表达式中删除了无用的反斜杠和括号,并在 char 类中使用了快捷方式:
#!/usr/bin/perl
use warnings;
use strict;
my $text = '{IS:cow}moo{\IS:cow}
{IS:cow}moo{\IS:cow}
{IS:dog}bark{\IS:dog}
{IS:dog}meow{\IS:dog}';
my %cnt;
my %animals;
while ( $text =~ /\{IS:([\w-]+)}(.*)\{\\IS:[\w-]+}/g ){
$animals{$1 . '_' . ++$cnt{$1}} = $2;
}
print "$_ => $animals{$_}\n" for sort keys %animals;
Run Code Online (Sandbox Code Playgroud)