When comparing performance of the solutions suggested for this question I discovered that StringExpression
involving Except
is two orders of magnitude slower for large strings as compared to equivalent RegularExpression
. Here is a simplified example demonstrating the problem:
With[{str = StringRepeat["a", 10^6] <> "b"}, {
AbsoluteTiming[StringMatchQ[str, Except["b"] .. ~~ "b"]][[1]],
AbsoluteTiming[StringMatchQ[str, RegularExpression["[^b]+b"]]][[1]]}]
Divide @@ %
{0.719855, 0.00323316} 222.648
The string pattern is 220 times slower than pure regex! But the regular expression [^x]+x
is the direct semantic translation of the string pattern Except["x"] .. ~~ "x"
, and this translation is unique and unambiguous. Why then the latter is so insanely slow?