Title here
Summary here
Java offers built-in support for regular expressions through the java.util.regex
package. Here are some examples of common regex-related tasks in Java.
import java.util.regex.*;
public class RegularExpressions {
public static void main(String[] args) {
// This tests whether a pattern matches a string.
boolean match = Pattern.matches("p([a-z]+)ch", "peach");
System.out.println(match);
// For other regex tasks, you'll need to compile a Pattern object.
Pattern r = Pattern.compile("p([a-z]+)ch");
// Many methods are available on these objects. Here's a match test like we saw earlier.
System.out.println(r.matcher("peach").matches());
// This finds the match for the regex.
Matcher m = r.matcher("peach punch");
if (m.find()) {
System.out.println(m.group());
}
// This also finds the first match but returns the start and end indexes for the match.
m = r.matcher("peach punch");
if (m.find()) {
System.out.println("idx: [" + m.start() + " " + m.end() + "]");
}
// The group methods include information about both the whole-pattern matches
// and the submatches within those matches.
m = r.matcher("peach punch");
if (m.find()) {
System.out.println("[" + m.group() + " " + m.group(1) + "]");
}
// To find all matches in the input, we can use a while loop with find().
m = r.matcher("peach punch pinch");
while (m.find()) {
System.out.print(m.group() + " ");
}
System.out.println();
// The replaceAll method can be used to replace subsets of strings with other values.
String newText = r.matcher("a peach").replaceAll("<fruit>");
System.out.println(newText);
// The replaceAll method with a lambda allows you to transform matched text with a given function.
String input = "a peach";
newText = r.matcher(input).replaceAll(matchResult -> matchResult.group().toUpperCase());
System.out.println(newText);
}
}
To run the program, compile and execute it using javac
and java
:
$ javac RegularExpressions.java
$ java RegularExpressions
true
true
peach
idx: [0 5]
[peach ea]
peach punch pinch
a <fruit>
a PEACH
For a complete reference on Java regular expressions, check the java.util.regex
package documentation.