View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
java
List list = new ArrayList();
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
java
String replaced = "Red Green Blue".replaceFirst("e", "*");

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
java
String replaced = text.replaceAll("se\\w+", "X");

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
java
Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}");
StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group(1)); rsb.reverse(); m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);