Capture offset of matches in std.regex.matchAll?

Justin Whear via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 8 08:58:47 PDT 2014


On Mon, 07 Jul 2014 21:32:29 +0000, JD wrote:

> I'm using a compile time regex to find some tags in an input string. Is
> it possible to capture the offset of the matches in some way? Otherwise
> I have to "calculate" the offsets myself by iterating over the results
> of matchAll.
> 
> Thanks,
> Jeroen
> 
> ---
> 
> Example code:
> 
> import std.stdio;
> import std.regex;
> 
> void main()
> {
> 	auto input = "<html><body><p>{{ message }}</p></body></html>";
> 	
> 	auto ctr = ctRegex!(`(\{\{|\{\%|\{\#)?`, "s");
> 
> 	auto matches = matchAll(input, ctr);
> 
>            /*
> 	auto offset = 0;
> 	foreach(match;matches)
> 	{
> 		writeln(offset, ":", match);
> 		++offset;
> 	}
>           */
> }

What do you mean by offset?  If you simply mean the index of the match, 
as your example seems to indicate, you can zip the matches with iota or 
sequence!"n".

If you want the offset in the string where each match begins I think 
you're out of luck.  I needed something similar a while ago and the best 
I could find was using the cumulative length of the pre property.


More information about the Digitalmars-d-learn mailing list