manimarank has asked for the wisdom of the Perl Monks concerning the following question:

Hi, how can we check the repetition of characters in a string, for example if the mail id is "xqwertyxyx@gmail.com" and we want to set the repetition "x" character is to 3, can anyone please give me the regex. thanks

Replies are listed 'Best First'.
Re: match repetetion of character
by moritz (Cardinal) on Jun 30, 2008 at 07:17 UTC
    You can efficiently count the number of occurrences of one character with the transliteration operator:
    use strict; use warnings; my $mail = 'xqwertyxyx@gmail.com'; my $count = ($mail =~ tr/x/x/); print "$count\n";
Re: match repetetion of character
by johngg (Canon) on Jun 30, 2008 at 09:29 UTC
    If you want to get the frequencies of all the letters in the name rather than just one in particular then use a hash and split. Here I have assumed that you are only interested in the name part of the address.

    use strict; use warnings; my $addr = q{xqwertyxyx@gmail.com}; my ( $name ) = $addr =~ m{^([^@]+)}; my %letterFreq; $letterFreq{ $_ } ++ for split m{}, $name; print map { qq{$_: $letterFreq{ $_ }\n} } sort { $letterFreq{ $b } <=> $letterFreq{ $a } || $a cmp $b } keys %letterFreq;

    The output.

    x: 3 y: 2 e: 1 q: 1 r: 1 t: 1 w: 1

    I hope this is useful.

    Cheers,

    JohnGG

Re: match repetetion of character
by Anonymous Monk on Jun 30, 2008 at 07:15 UTC
    C:\>perldoc -q count Found in C:\Perl\lib\pod\perlfaq4.pod How can I count the number of occurrences of a substring within a st +ring? There are a number of ways, with varying efficiency. If you want a + count of a certain single character (X) within a string, you can use the "tr///" function like so: $string = "ThisXlineXhasXsomeXx'sXinXit"; $count = ($string =~ tr/X//); print "There are $count X characters in the string"; This is fine if you are just looking for a single character. Howev +er, if you are trying to count multiple character substrings within a lar +ger string, "tr///" won't work. What you can do is wrap a while() loop around a global pattern match. For example, let's count negative integers: $string = "-9 55 48 -2 23 -76 4 14 -44"; while ($string =~ /-\d+/g) { $count++ } print "There are $count negative numbers in the string"; Another version uses a global match in list context, then assigns +the result to a scalar, producing a count of the number of matches. $count = () = $string =~ /-\d+/g;