I\'m new to Java. As a .Net developer, I\'m very much used to the Regex class in .Net. The Java implementation of Regex (Regular Expressions) is no
One can rant, or one can simply write:
public class Regex {
/**
* @param source
* the string to scan
* @param pattern
* the regular expression to scan for
* @return the matched
*/
public static Iterable matches(final String source, final String pattern) {
final Pattern p = Pattern.compile(pattern);
final Matcher m = p.matcher(source);
return new Iterable() {
@Override
public Iterator iterator() {
return new Iterator() {
@Override
public boolean hasNext() {
return m.find();
}
@Override
public String next() {
return source.substring(m.start(), m.end());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
Used as you wish:
public class RegexTest {
@Test
public void test() {
String source = "The colour of my bag matches the color of my shirt!";
String pattern = "colou?r";
for (String match : Regex.matches(source, pattern)) {
System.out.println(match);
}
}
}