Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Welcome to the Monastery
 
PerlMonks  

Re: counting overlapping patterns

by Limbic~Region (Chancellor)
on Feb 18, 2005 at 15:30 UTC ( [id://432504]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to counting overlapping patterns

Anonymous Monk,
Here is some code that covers your example, but it admittedly only works on fixed strings since it doesn't use regular expressions at all.
#!/usr/bin/perl use strict; use warnings; print str_count('AAAA', 'AA'), "\n"; sub str_count { my ($str, $pat) = @_; my $tot; for ( 0 .. length( $str ) - length( $pat ) ) { $tot++ if index($str, $pat, $_) - $_ == 0;; } return $tot; }

Cheers - L~R

Replies are listed 'Best First'.
Re^2: counting overlapping patterns
by Limbic~Region (Chancellor) on Feb 19, 2005 at 11:14 UTC
    While discussing other methods that avoided regular expressions in the CB with bobf and nothingmuch, I mentioned an unpack/hash solution. nothinmuch asked to see it, so here is a highly untested alternative.
    #!/usr/bin/perl use strict; use warnings; print str_count('ABAABAAAA', 'AA'), "\n"; sub str_count { my ($str, $pat) = @_; my %substr; my ($p_len, $s_len) = (length $pat, length $str); my $template = ("A$p_len" . 'X' . ($p_len - 1)) x ($s_len - $p_len + + 1); $substr{$_}++ for unpack $template, $str; return $substr{$pat}; }

    Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://432504]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.