String patternString = "hello [wW]orld"; Pattern pattern = Pattern.compile(patternString); String input = "Hello World"; boolean matches = pattern.matcher(input).matches(); System.out.println(matches); // prints "true"
String patternString = "foo.+?baz"; Pattern pattern = Pattern.compile(patternString); String input = "foo123baz foo456baz"; String replacement = "qux"; String replaced = pattern.matcher(input).replaceAll(replacement); System.out.println(replaced); // prints "qux qux"This code creates a regular expression pattern that matches "foo" followed by any characters (the .+? part) until it reaches "baz". It then compiles this pattern into a Pattern object and uses it to create a Matcher object with the input string "foo123baz foo456baz". It replaces every match with the string "qux" using the replaceAll() method of the Matcher object. The java.util.regex Pattern class is a part of the java.util library.