Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to iterate over regexp compliant strings
    text
    copied!<p>What is the easiest way to implement a class (in Java) that would serve as an iterator over the set of all values which conform to a given regexp?</p> <p>Let's say I have a class like this:</p> <pre><code>public class RegexpIterator { private String regexp; public RegexpIterator(String regexp) { this.regexp = regexp; } public abstract boolean hasNext() { ... } public abstract String next() { ... } } </code></pre> <p>How do I implement it? The class assumes some linear ordering on the set of all conforming values and the next() method should return the i-th value when called for the i-th time.</p> <p>Ideally the solution should support full regexp syntax (as supported by the Java SDK).</p> <hr> <p>To avoid confusion, please note that the class is not supposed to iterate over matches of the given regexp over a given string. Rather it should (eventually) enumerate all string values that conform to the regexp (i.e. would be accepted by the matches() method of a matcher), without any other input string given as argument.</p> <hr> <p>To further clarify the question, let's show a simple example.</p> <pre><code>RegexpIterator it = new RegexpIterator("ab?cd?e"); while (it.hasNext()) { System.out.println(it.next()); } </code></pre> <p>This code snippet should have the following output (the order of lines is not relevant, even though a solution which would list shorter strings first would be preferred).</p> <pre><code>ace abce ecde abcde </code></pre> <hr> <p>Note that with some regexps, such as <code>ab[A-Z]*cd</code>, the set of values over which the class is to iterate is ininite. The preceeding code snippet would run forever in these cases.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload