Chinaunix

标题: perl如何查找字符串的个数 [打印本页]

作者: jackbrown    时间: 2010-11-09 19:54
标题: perl如何查找字符串的个数
本帖最后由 jackbrown 于 2010-11-09 19:55 编辑

我们有一个txt文件
  1. TAGAGCCTAGAAAAAAGTTACATGA 1250 1 chrY:11921135 F
  2. GAAAAACAGGAACATTGTAGAGGAA 1250 1 chrY:11780373 F
复制代码
如何找出里面AAAA的个数,其中AAAAAA表示有3个AAAA

我本来是这样写的
  1. #!/usr/bin/perl
  2. open(ctr,'sss.txt')||die("Could not open sss.txt");
  3. $text=<ctr>;
  4. while($text)
  5. {
  6.         $count++ while $text =~/AAAA/g;
  7.         $text=<ctr>;
  8. }
  9. print"the number of AAAA is $count";
  10. close ctr;
复制代码
但发现那种重复的好像不能正确的计算,不知道应该如何改进?
作者: shijiang1130    时间: 2010-11-09 20:10
回复 1# jackbrown

是和?=有关的.我找找啊
作者: shijiang1130    时间: 2010-11-09 20:16
  1. #!/usr/bin/perl
  2. open(ctr,'sss.txt')||die("Could not open sss.txt");
  3. $text=<ctr>;
  4. while($text)
  5. {
  6.         $count++ while $text =~/(?=AAAA)/g;
  7.         $text=<ctr>;
  8. }
  9. print"the number of AAAA is $count";
  10. close ctr;
复制代码
回复 2# shijiang1130
作者: jackbrown    时间: 2010-11-09 20:20
回复 3# shijiang1130


    真是谢谢呀,弄了很长时间也不会!这次终于会了!
作者: longjinjiu    时间: 2010-11-09 23:35
I tried this:

my $count = 0;
while($str =~ /A{4,}/sg)
{
        $count += length($&) - 3;
}
print $count;
作者: alleva    时间: 2010-11-10 08:17
学习了
作者: toniz    时间: 2010-11-10 09:29
开拓下思维吧,应该还有蛮多写法的。
  1. $text='asdfasAAAAAADSFAAAADFDSAFEA AAAAA';
  2. $text =~/(?{$count++ })AAAA(?!)/;
  3. print"the number of AAAA is $count";
复制代码

作者: Bruceh2010    时间: 2010-11-10 09:30
答案是多少啊楼主 ,是4么?
作者: 小鹭    时间: 2010-11-10 17:09
$str="TAAAGAGCCTAGAAAAAAGTTACATGA 1250 1 chrY:11921135 F";
$count = $str =~ s/AAA//g;
print "$count\n";
作者: DIYBYPERL    时间: 2010-11-13 15:28
这样应该可以
  1. $_='TAAAAAGAGCCTAGAAAAAAGTTACATGA 1250 1 chrY:11921135 F';
  2. print scalar ( ()=/A(?=AAA)/g ),"\n";
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2