Java - Regular Expressions Part 1: Understanding the Basics of Regex in Java
Key Classes in java.util.regex:
Pattern: Compiles a regex into a reusable pattern.
Matcher: Matches the compiled pattern against the text.
PatternSyntaxException: Catches invalid regex syntax.
Example 1: Simple Match
String pattern = "hello";
String text = "hello world";
boolean matches = text.matches(".*" + pattern + ".*"); // true
System.out.println("Match found: " + matches);
Example 2: Case Sensitivity
String pattern = "Hello";
String text = "hello world";
boolean matches = text.matches(".*" + pattern + ".*"); // false
System.out.println("Case-sensitive match: " + matches);
Example 3: Compiling a Pattern
Pattern pattern = Pattern.compile("java");
Matcher matcher = pattern.matcher("I love java programming");
System.out.println("Match found: " + matcher.find()); // true