davido did an excellent job detailing the step-by-step creation of a general regex that would count your abc\d+ pattern within a line. However, I get the impression that you'd like a specific count of the number of occurrences for abc1 .. abc10 within a line.

davido indicated that your regex would only match abc followed by either a 1 or a 0, so it's not going to match all of abc10. Perhaps I'm over-simplifying the issue, but I'd likely use the following to count the number of times abc10 occurs within a line of text:

my @find = $line[$i] =~ /\babc10\b/g;

This regex will match your abc10 surrounded by a word boundary. Consider the following test for this regex:

use Modern::Perl; my @patterns = map "abc$_", 1 .. 10; my $str = join ' ', map { $_ = int( rand(10) ) + 1; "abc$_" } 1 .. 25; say "String:\n$str\n\nContains:"; say "$_: " . @{ [ $str =~ /\b$_\b/g ] } for @patterns;

Output:

String: abc9 abc6 abc2 abc7 abc3 abc10 abc2 abc10 abc1 abc3 abc2 abc1 abc4 abc +4 abc2 abc4 abc8 abc10 abc10 abc7 abc3 abc10 abc6 abc1 abc8 Contains: abc1: 3 abc2: 4 abc3: 3 abc4: 3 abc5: 0 abc6: 2 abc7: 2 abc8: 2 abc9: 1 abc10: 5

The script first generates a string of 25 random instances of the patterns (abc1 .. abc10) your interested in counting. It ends by looping through each pattern, using the regex (like the above) to provide a count of each occurrence of abc1 .. abc10 within that string.

Hope this helps!


In reply to Re: problem with regex by Kenosis
in thread problem with regex by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.