Re: regex puzzle
On Thursday, April 10, 2014 4:07:30 AM UTC+2, markspace wrote:
This is the type of solution I'm used to seeing for problems of this
type. Roedy said he didn't want to match substrings (so "2009" should
not be matched. I think you just have to add some "not digit" to the
outside of that.
"\\D([1-9]|1[0-9]|20)\\D"
But better use lookaround for that:
package regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RoedyNumberMatch {
private static final String[] P_FIXES = { "", "foo", "bar ", "20" };
private static final Pattern PAT = Pattern
.compile("(?<!\\d)(?:20|1\\d|[1-9])(?!\\d)");
public static void main(String[] args) {
final Matcher m = PAT.matcher("");
for (int i = 0; i < 30; ++i) {
System.out.println("i = " + i);
for (final String pre : P_FIXES) {
for (final String post : P_FIXES) {
final String s = pre + i + post;
System.out.println("s = '" + s + "'");
if (m.reset(s).matches()) {
System.out.println("Matches: '" + m.group() + "'");
}
if (m.reset(s).find()) {
System.out.println("Finds: '" + m.group() + "'");
}
}
}
System.out.println();
}
}
}
Also here: https://gist.github.com/rklemme/10451386
Cheers
robert