I have an array of words I need to do a find-and-replace by regex operation on, and sometimes this array can be thousands of words long. I’ve tested and found that stemming the words using common prefixes is much faster than searching for them individually. That is, ^where|why$ is slower than ^wh(ere|y)$. Obviously it’s not a noticeable difference in such a short example, but it’s considerably faster where there are thousands of alternatives and the subject string is long.
So I’m looking for a way to do this stemming automatically, for instance to convert a string[] { "what", "why", "where", "when", "which" } into wh(at|y|e(re|n)|i(ch))
Is there already a recognized algorithm out there that does this ? If not, how would you go about it ? It seems to need to be done recursively but I can’t quite get my head round how to do it. I have a method I wrote that works to a limited extent, but it’s inelegant, 60 lines longs and uses multiple nested foreach loops so it’s a future maintenance nightmare. I’m sure there’s a much better way, if anyone could point me in the right direction that’d be much appreciated…
This code should work:
Usage:
EDIT:
to get
reg2 = "wh(y|at|e(re|n))|a(bc|pple)"i.e. without the first wrapping brackets, just uncomment the marked line inBuildRexpmethod.