import java.util.regex.Pattern; String input = "abc123xyz"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.print(matcher.group()); // Output: 123 }
import java.util.regex.Pattern; String input = "Hello, world!"; Pattern pattern = Pattern.compile("\\s+"); String replaced = pattern.matcher(input).replaceAll("-"); System.out.println(replaced); // Output: Hello,-world!This code replaces all occurrences of spaces in a string with a hyphen using Pattern and Matcher classes. The regular expression used is "\\\\s+" which matches one or more whitespace characters. In conclusion, the java.util.regex Pattern is a package library in Java that provides classes to work with regular expressions. It's useful for searching, matching and manipulating text.