Java - Regular Expressions Part 2: Core Regex Syntax and Metacharacters
Metacharacters:
.: Matches any character except a newline.
^ and $: Anchor the match at the start or end of the string.
[]: Matches any character in the set.
Example 1: Dot Metacharacter
String pattern = ".ar";
String text = "car";
System.out.println(text.matches(pattern)); // true
Example 2: Anchors
String pattern = "^hello";
String text = "hello world";
System.out.println(text.matches(pattern + ".*")); // true
Example 3: Character Set
String pattern = "[aeiou]";
String text = "hello";
System.out.println(text.matches(".*" + pattern + ".*")); // true
Example 4: Quantifiers
*: Matches 0 or more times.
+: Matches 1 or more times.
{n}: Matches exactly n times.
String pattern = "a+b*";
System.out.println("aaab".matches(pattern)); // true
System.out.println("b".matches(pattern)); // false