find regex in backward direction ?

kdevel kdevel at vogtner.de
Sat Dec 19 23:16:18 UTC 2020


On Saturday, 19 December 2020 at 12:52:54 UTC, Виталий Фадеев 
wrote:
> Goal:
>     size_t pos = findRegexBackward( r"abc"d );
>     assert( pos == 4 );


module LastOccurrence;

size_t findRegexBackward_1 (dstring s, dstring pattern)
{
    import std.regex : matchAll;
    auto results = matchAll (s, pattern);
    if (results.empty)
       throw new Exception ("could not match");
    size_t siz;
    foreach (rm; results)
       siz = rm.pre.length;
    return siz;
}

size_t findRegexBackward_2 (dstring s, dstring pattern)
// this does not work with irreversible patterns ...
{
    import std.regex : matchFirst;
    import std.array : array;
    import std.range: retro;
    auto result = matchFirst (s.retro.array, pattern.retro.array);
    if (result.empty)
       throw new Exception ("could not match");
    return result.post.length;
}

unittest {
    import std.exception : assertThrown;
    static foreach (f; [&findRegexBackward_1, 
&findRegexBackward_2]) {
       assert (f ("abc3abc7", r""d) == 8);
       assert (f ("abc3abc7", r"abc"d) == 4);
       assertThrown (f ("abc3abc7", r"abx"d));
       assert (f ("abababababab", r"ab"d) == 10);
    }
}


More information about the Digitalmars-d-learn mailing list