String input = "Hello, world!"; Pattern pattern = Pattern.compile("world"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { System.out.println("Pattern found!"); }
String input = "Name: John Doe, Age: 30"; Pattern pattern = Pattern.compile("Name: ([\\w\\s]+), Age: (\\d+)"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { String name = matcher.group(1); int age = Integer.parseInt(matcher.group(2)); System.out.println("Name: " + name); System.out.println("Age: " + age); }In this example, we create a pattern object that matches a string containing a person's name, followed by their age. We use two capture groups to extract the name and age separately from the input string. The group() method returns the matched text for each capture group. Package Library: java.util.regex