String input = "Hello, World!"; String regex = "^Hello.*$"; // matches string that starts with "Hello" and ends with any sequence of characters boolean isMatch = Pattern.matches(regex, input); System.out.println(isMatch); // Output: true
String input = "Email: [email protected]"; String regex = "\\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,})\\b"; // matches email addresses Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); if (matcher.find()) { String email = matcher.group(1); System.out.println(email); // Output: [email protected] }In both examples, the java.util.regex package library is used. The Pattern.matches method in Example 1 checks if a string matches a regular expression. The Pattern.compile and Matcher.find methods are used in Example 2 to extract a substring that matches a regular expression.