Regular Expressions in Java
- April 28th, 2010
- Write comment
Need to use regular expressions (regex) for common tasks in Java?
Here is a quick example:
import java.util.regex.Pattern import java.util.regex.Matcher // ... Pattern pattern = Pattern.compile("pattern"); Matcher matcher = pattern.matcher("subject"); // find (sub)matches while(matcher.find()) { String nth_match = matcher.group(); } // veryfy that the whole subject matches the pattern Boolean does_it_matches = matcher.matches() // replace all the occurrence of a regex in a String (no import needed) "string instance".replaceAll("regex","replacement");
For other tasks take a look at the Matcher class javadoc.


