in reply to problem with regex
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!
|
|---|