Chinaunix
标题:
单行匹配多次的问题
[打印本页]
作者:
grshrd49
时间:
2013-09-13 15:28
标题:
单行匹配多次的问题
本帖最后由 grshrd49 于 2013-09-13 15:28 编辑
我想计算出字符串中单词a和b的数量,是不是只有用这样的两次循环呢? 有没有更好的方法来做?
$s = "aaabbbaacccbbbddaadeee";
$an = 0;
$bn = 0;
$an++ while($s =~ /a/g);
$bn++ while($s =~ /b/g);
复制代码
作者:
iamlimeng
时间:
2013-09-13 15:42
$s = "aaabbbaacccbbbddaadeee";
$an = () = ($s =~ /a/g);
print "$an\n";
复制代码
作者:
jason680
时间:
2013-09-13 15:49
回复
1#
grshrd49
Would you like this ...
# perl cnt.pl
a=7
b=6
# cat cnt.pl
use strict;
use warnings;
$_ = "aaabbbaacccbbbddaadeee";
my @aCnt = qw/a b/;
my %hCnt = map { $_ => 0 } @aCnt;
while(m/(.)/g){
$hCnt{$1}++ if(exists $hCnt{$1});
}
foreach(@aCnt){
print "$_=$hCnt{$_}\n";
}
作者:
grshrd49
时间:
2013-09-13 15:57
回复
3#
jason680
这个有意思!
定义一个hash 然后循环这个字符串 验证是否存在与hash列表中的key
作者:
grshrd49
时间:
2013-09-13 15:58
回复
2#
iamlimeng
这个是只匹配了一个单词呀?
作者:
yinyuemi
时间:
2013-09-13 17:21
本帖最后由 yinyuemi 于 2013-09-13 17:21 编辑
回复
1#
grshrd49
perl -le '$s = "aaabbbaacccbbbddaadeee";
$h{$&}++ while $s=~/./g;
print $h{b};
print $h{a}'
6
7
复制代码
作者:
grshrd49
时间:
2013-09-13 17:34
回复
6#
yinyuemi
不是看得懂你的写法 能稍微解释一下嘛
作者:
lucash
时间:
2013-09-14 12:01
my $hash;
$s =~ /(a|b)(*PRUNE)(?{$hash->{$&}++})(*FAIL)/;
print $hash->{'a'}
print $hash->{'b'}
作者:
104359176
时间:
2013-09-14 14:51
为什么要追求更多的解决一个问题的方法呢?
作者:
afukada
时间:
2013-09-14 15:10
取代加字串長度?
$s="aaabbbaacccbbbddaadeee";
foreach("a","b")
{
($st=$s)=~s/$_//g;
print $_,"\t",length($s)-length($st),"\n";
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2