www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Counting number of regular expressions matches

reply Alain De Vos <devosalain71 gmail.com> writes:
I've got,
import std.regex: regex,matchAll;
...
string regfiltertext="\\b"~entryfilter.getText()~"\\b";
auto reg = regex(regfiltertext);
auto result = name.strip("_").matchAll(reg);
int t=0;
foreach (c; result) t+=1;

This make t the number of regular expressions matches.
Is there a better way to have the number of matches ?
Apr 09 2021
parent Mitacha <mateusz.mitaszka gmail.com> writes:
On Friday, 9 April 2021 at 15:01:58 UTC, Alain De Vos wrote:
 I've got,
 import std.regex: regex,matchAll;
 ...
 string regfiltertext="\\b"~entryfilter.getText()~"\\b";
 auto reg = regex(regfiltertext);
 auto result = name.strip("_").matchAll(reg);
 int t=0;
 foreach (c; result) t+=1;

 This make t the number of regular expressions matches.
 Is there a better way to have the number of matches ?
`matchAll` returns `RegexMatch` which is a ForwardRange, so it should be possible to get it's length using `walkLength`. ```d auto r = regex(`([a-z])a`); auto result = "banana".matchAll(r); writeln(result); // [["ba", "b"], ["na", "n"], ["na", "n"]] writeln(result.walkLength); // 3 ``` I'm not familiar with using matches with `std.regex`, but I hope this solves your problem.
Apr 09 2021