Top 10 Java Regex Interview Questions - Explained
1. Validate Email Address
^ // Start of string
[\w.-]+ // One or more of: word characters, dot, hyphen (local part of email)
@ // Literal '@' symbol
[\w.-]+ // One or more of: word characters, dot, hyphen (domain name)
\. // Literal dot before domain extension
\w+ // One or more word characters (e.g., com, org, net)
$ // End of string
2. Extract All Numbers from a String
\d // A digit (0-9)
+ // One or more of the preceding (digits grouped together)
3. Validate IPv4 Address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}
(25[0-5]|2[0-4]\d|[01]?\d\d?)$
^ // Start of string
(25[0-5]|2[0-4]\d|[01]?\d\d?) // Each octet: 0-255
\. // Literal dot
{3} // Repeat 3 times
(...) // Final octet
$ // End of string
4. Validate Strong Password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$
^ // Start
(?=.*[a-z]) // At least one lowercase letter
(?=.*[A-Z]) // At least one uppercase letter
(?=.*\d) // At least one digit
(?=.*[@$!%*?&]) // At least one special char
.{8,} // At least 8 characters
$ // End
5. Match Hex Color Codes
^#(?:[0-9a-fA-F]{3}){1,2}$
# // Starts with hash
(?:[0-9a-fA-F]{3}) // Match 3 or 6 hex digits
{1,2} // Repeat once or twice
6. Extract HTML Tags
<[^>]+>
< // Opening bracket
[^>]+ // Anything except >
> // Closing bracket
7. Split by Comma, Space, or Semicolon
[,;\s]+
[ ,;\s] // Match comma, semicolon or space
+ // One or more
8. Alphanumeric Only (No Symbols)
^[a-zA-Z0-9]+$
^ // Start
[a-zA-Z0-9]+ // Letters or digits
$ // End
9. Validate Date (dd-mm-yyyy)
^\d{2}-\d{2}-\d{4}$
^ // Start
\d{2} // Two digits (day)
- // Hyphen
\d{2} // Two digits (month)
- // Hyphen
\d{4} // Four digits (year)
$ // End
10. Find Duplicate Words
\b(\w+)\s+\1\b
\b // Word boundary
(\w+) // First word (captured)
\s+ // Space(s)
\1 // Repeat captured word
\b // Word boundary