Pattern pattern = Pattern.compile("hello"); Matcher matcher = pattern.matcher("hello world"); if (matcher.matches()) { System.out.println("Match found!"); } else { System.out.println("No match found."); }
Pattern pattern = Pattern.compile("(?\\w+) (? \\w+)"); Matcher matcher = pattern.matcher("John Doe"); if (matcher.matches()) { String firstName = matcher.group("first"); String lastName = matcher.group("last"); System.out.println("First name: " + firstName); System.out.println("Last name: " + lastName); } else { System.out.println("No match found."); }
Pattern pattern = Pattern.compile("\\s+"); String[] words = pattern.split("The quick brown fox"); for (String word : words) { System.out.println(word); }In these examples, `java.util.regex` is the package library being used.