4 ms·
Your implementation seems complicated. The regular expression "foo(bar|quux)*" denotes a set of strings: { "foo", "foobar", "fooquux", "foobarbar", "foobarquux"
by kazinator 9y ago
Your implementation seems complicated. The regular expression "foo(bar|quux)*" denotes a set of strings: { "foo", "foobar", "fooquux", "foobarbar", "foobarquux", "fooquuxbar", "fooquuxquux", ... }
Since this is anchored to the right, we can look at this from right to left: it's any mixture, including empty, of "quux" or "bar" elements, preceded by "foo". From this, a very simple algorithm pops out:
while (string does not end with "foo") {
if (string ends with "quux")
chop off "quux" from end of string
else if (string ends with "bar")
chop off "bar" from end of string
else
return "no match"
}
return "match"
- Xophmeister 9y agoMy implementation was the first thing that popped into my head. Yours works too (although note that yours will probably reallocate memory every time it chops the end off the string, so it'll be slower). A RD parser or finite state machine would also work. My point was rather that regular expressions are a much better tool for this type of task (see the reasons given at the end of my previous comment). Writing fewer lines of code to do the same job is usually a good idea, providing it remains understandable. Personally, I find the syntax of regular expressions pretty straightforward and a lot of languages even allow you write comments within them to make them even easier to follow.
- deleted 9y ago[deleted]