
Java RegEx Tester
Test and debug Java regular expressions instantly using the Qodex Java RegEx Tester, powered by the java.util.regex engine. Get real-time feedback with match highlights, capture groups, and syntax error detection—making it ideal for tasks like email validation, password matching, and pattern-based string parsing.
Whether you're building login forms, input validators, or custom parsers, this tool streamlines your Java regex workflow. For comprehensive testing, pair it with the Email Generator, UUID Generator, or Password Generator to generate realistic test inputs.
Fine-tune specific fields with our Email Regex Java Validator or Phone Number Regex Java Validator to ensure your patterns are both precise and production-ready.
Java RegEx Tester - Documentation
Java Regex Tester
The Java Regex Tester by Qodex helps developers write, test, and debug regular expressions in real time using Java's java.util.regex package. It supports instant pattern testing for emails, passwords, phone numbers, dates, credit cards, and more.
You can view live match results, capture groups, and syntax feedback instantly—making it easy to refine your regex before using it in Java code.
Important Note: This tool runs in the browser using the JavaScript regex engine, which differs from Java's
java.util.regexin several ways. Key differences to be aware of:
Possessive quantifiers (
*+,++,?+) are supported in Java but not in JavaScriptAtomic groups (
(?>...)) work in Java but not in JavaScriptUnicode property classes like
\p{IsGreek}or\p{Sc}have broader support in JavaBackreference syntax differs in replacement strings: Java uses
$1, JavaScript uses$1(same), but Java also supports\1in the patternFlags: Java supports
Pattern.CANON_EQandPattern.UNIX_LINESwhich have no JS equivalentFor production Java code, always verify patterns using
Pattern.compile()in your IDE or a Java runtime environment.
How to Use:
Enter your regular expression.
Provide a test string.
Instantly see highlighted matches and capture groups.
Need test inputs? Try our:
Java Regex Quick Reference / Cheat Sheet
Bookmark this table for quick lookups when writing Java regex patterns:
Pattern | Description | Example | Matches |
|---|---|---|---|
| Any character except newline |
| cat, cot, cut |
| Any digit [0-9] |
| 123, 456 |
| Any non-digit |
| abc, hello |
| Word char [a-zA-Z0-9_] |
| hello_42 |
| Non-word character |
| @, #, ! |
| Whitespace (space, tab, newline) |
| spaces, tabs |
| Non-whitespace |
| hello |
| Start of string/line |
| Hello at start |
| End of string/line |
| world at end |
| Word boundary |
| cat (not cats) |
| Character class |
| any vowel |
| Negated class |
| non-digit |
| Range |
| any letter |
| 0 or more (greedy) |
| ac, abc, abbc |
| 1 or more (greedy) |
| abc, abbc |
| 0 or 1 (optional) |
| color, colour |
| Exactly n times |
| 2024 |
| Between n and m times |
| 12, 123, 1234 |
| 0 or more (lazy) |
| shortest tag |
| Capturing group |
| groups: 12, 34 |
| Non-capturing group |
| ab, abab |
| Positive lookahead |
| 5 in 5px |
| Negative lookahead |
| foo not before bar |
| Positive lookbehind |
| domain after @ |
| Negative lookbehind |
| px not after digit |
| Any Unicode letter |
| Hello, 你好 |
| Backreference to group 1 |
| hello hello |
Java Regex Syntax Essentials
Meta characters
.: Matches any single character except newline characters. Commonly used to represent any wildcard character.^: Anchors the match at the beginning of a line or string. Example:^abcmatchesabconly if it's at the start.$: Anchors the match at the end of a line or string. Example:xyz$matchesxyzonly at the end.|: Acts as a logical OR operator. Example:cat|dogmatches either cat or dog.
Character Classes
[abc]: Matches any one character: eithera,b, orc.[^abc]: Matches any character excepta,b, orc.[a-zA-Z]: Specifies a range, matches any uppercase or lowercase letter from a to z.
Predefined Character Classes
\d: Matches any digit character; equivalent to[0-9].\D: Matches any non-digit character; equivalent to[^0-9].\s: Matches any whitespace character (space, tab, newline).\S: Matches any non-whitespace character.\w: Matches any word character (letters, digits, or underscore); equivalent to[a-zA-Z0-9_].\W: Matches any character that is not a word character.
Quantifiers
*: Matches the preceding element zero or more times. Example:lo*lmatchesll,lol,lool, etc.+: Matches one or more occurrences. Example:lo+lmatcheslol,lool, but notll.?: Matches zero or one occurrence. Also makes quantifiers lazy when placed after them.{n}: Matches exactly n occurrences. Example:a{3}matchesaaa.{n,}: Matches n or more occurrences.{n,m}: Matches between n and m occurrences.
Groups and Capturing
(abc): Captures and groups the match forabc. Can be reused with backreferences.(?:abc): Groupsabcwithout capturing it. Useful for applying quantifiers without creating references.(?i)abc: Enables case-insensitive matching for the group.\b: A word boundary.\B: A non-word boundary.\1,\2, etc.: Backreferences to captured groups. Example:(\w+)\s\1matches repeated words likehello hello.
Logical Assertions (Lookaheads and Lookbehinds)
(?=...): Positive lookahead. Ensures what follows the current position matches the pattern inside. Example:\d(?=px)matches a digit only if followed bypx.(?!...): Negative lookahead. Ensures the following characters do not match the pattern. Example:foo(?!bar)matchesfooonly if not followed bybar.(?<=...): Positive lookbehind. Ensures that what precedes the current position matches the pattern. Example:(?<=@)\w+matches the username after an@.(?<!...): Negative lookbehind. Ensures that what precedes is not a match.
Greedy vs Lazy Quantifiers
*?: Matches as few as possible, zero or more times.+?: Matches as few as possible, one or more times.??: Matches as few as possible, zero or one time.{n,m}?: Matches between n and m times, choosing the smallest match possible.
Lazy quantifiers are useful when you're trying to avoid consuming too much text, especially helpful for nested tags or repeated delimiters.
Unicode Support
\p{L}: Matches any kind of letter from any language.\p{N}: Matches any kind of numeric character.\p{IsGreek}: Matches any character in the Greek Unicode block.\P{...}: The inverse of\p{...}.
Unicode properties allow your regex to work globally, great for international applications.
Common Java Regex Examples
Each example below includes complete, runnable Java code you can copy into your IDE.
1. Email Validation
Use with Email Regex Java Validator
import java.util.regex.*;
public class EmailValidator { public static void main(String[] args) { String email = "test@example.com"; Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"); Matcher matcher = pattern.matcher(email); System.out.println("Email valid: " + matcher.matches()); // true } }
2. Strong Password Check
Test using Password Regex Java Validator
import java.util.regex.*;
public class PasswordValidator { public static void main(String[] args) { String password = "Str0ng@Pass!"; String regex = "(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}"; boolean isStrong = password.matches(regex); System.out.println("Password strong: " + isStrong); // true } }
3. Phone Number Formats
Covers (123) 456-7890, 1234567890, 123-456-7890:
import java.util.regex.*;
public class PhoneValidator { public static void main(String[] args) { String[] phones = {"(123) 456-7890", "1234567890", "123-456-7890"}; Pattern pattern = Pattern.compile( "^(\d{10}|\(\d{3}\)[\s.-]?\d{3}[\s.-]\d{4}|\d{3}[\s.-]\d{3}[\s.-]\d{4})$" ); for (String phone : phones) { System.out.println(phone + " valid: " + pattern.matcher(phone).matches()); } } }
4. Credit Card Pattern Matching (Visa)
Use Credit Card Regex Java Validator + Luhn check for full validation.
import java.util.regex.*;
public class CreditCardValidator { public static void main(String[] args) { String card = "4111111111111111"; Pattern visa = Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$"); System.out.println("Visa valid: " + visa.matcher(card).matches()); // true } }
5. Date Formats (ISO / US)
Regex checks format only. Use Java date libraries for calendar validation (e.g., leap years).
import java.util.regex.*;public class DateValidator { public static void main(String[] args) { String isoDate = "2024-12-25"; String usDate = "12/25/2024";
Pattern isoPattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}"); Pattern usPattern = Pattern.compile("\\d{2}/\\d{2}/\\d{4}"); System.out.println("ISO valid: " + isoPattern.matcher(isoDate).matches()); // true System.out.println("US valid: " + usPattern.matcher(usDate).matches()); // true }
}
6. Extract Filename from Windows Path
import java.util.regex.*;
public class FilenameExtractor { public static void main(String[] args) { String path = "C:\Users\Bob\Documents\presentation_final.pptx"; Pattern pattern = Pattern.compile("[^\\]+$"); Matcher matcher = pattern.matcher(path); if (matcher.find()) { System.out.println("Filename: " + matcher.group()); // presentation_final.pptx } } }
7. IPv4 Address Validation
import java.util.regex.*;public class IPv4Validator { public static void main(String[] args) { String ip = "192.168.1.1"; String regex = "^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$"; System.out.println(ip + " valid: " + ip.matches(regex)); // true
String badIp = "999.999.999.999"; System.out.println(badIp + " valid: " + badIp.matches(regex)); // false }
}
8. Validating 24-hour Time Format (HH:MM)
import java.util.regex.*;
public class TimeValidator { public static void main(String[] args) { String[] times = {"14:45", "09:02", "24:00", "00:00"}; Pattern pattern = Pattern.compile("^([01]\d|2[0-3]):[0-5]\d$"); for (String time : times) { System.out.println(time + " valid: " + pattern.matcher(time).matches()); } // 14:45 valid: true // 09:02 valid: true // 24:00 valid: false // 00:00 valid: true } }
9. Validate Hex Colors
import java.util.regex.*;
public class HexColorValidator { public static void main(String[] args) { String[] colors = {"#1a2B3c", "123", "#ABCDEF", "#zzz", "FFF0A"}; Pattern hexPattern = Pattern.compile("^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$"); for (String color : colors) { Matcher matcher = hexPattern.matcher(color); System.out.println(color + " is valid hex: " + matcher.matches()); } } }
10. SSN / ZIP Code Patterns
Format checking only. Use these patterns:
import java.util.regex.*;public class FormatValidator { public static void main(String[] args) { // SSN: 123-45-6789 or 123456789 String ssn = "123-45-6789"; System.out.println("SSN valid: " + ssn.matches("^\d{3}-?\d{2}-?\d{4}$")); // true
// ZIP+4: 12345 or 12345-6789 String zip = "12345-6789"; System.out.println("ZIP valid: " + zip.matches("^\\d{5}(-\\d{4})?$")); // true // Canadian Postal Code: A1B 2C3 String postal = "K1A 0B1"; System.out.println("Postal valid: " + postal.matches( "^[ABCEGHJ-NPRSTVXY]\\d[ABCEGHJ-NPRSTV-Z]\\s?\\d[ABCEGHJ-NPRSTV-Z]\\d$" )); // true }
}
11. Removing HTML Tags from a String
import java.util.regex.*;
public class HtmlStripper { public static void main(String[] args) { String html = "<p>Hello <b>World</b></p>"; String cleaned = html.replaceAll("<[^>]+>", ""); System.out.println(cleaned); // Hello World } }
12. Removing Blank Lines from a String
import java.util.regex.*;
public class BlankLineRemover { public static void main(String[] args) { String messyText = "Line one.\n\n\nLine two after blanks.\n\nLine three."; String cleaned = messyText.replaceAll("(?m)^\s*$\n+", ""); System.out.println(cleaned); // Line one. // Line two after blanks. // Line three. } }
13. Validate Feet and Inches Notation
import java.util.regex.*;
public class HeightValidator { public static void main(String[] args) { String[] heights = {"6'2"", "5'11"", "0'0"", "6'13""}; Pattern pattern = Pattern.compile("^\d+'(\d|1[01])"$"); for (String h : heights) { System.out.println(h + " valid: " + pattern.matcher(h).matches()); } // 6'2" valid: true // 5'11" valid: true // 0'0" valid: true // 6'13" valid: false } }
Common Patterns for Number Validation
Regular expressions are invaluable for validating and parsing numbers of various formats. Here are frequently used patterns:
Pattern | Description | Example Matches |
|---|---|---|
| Positive integers (any length) | 123, 987654 |
| Positive integers (max 10 digits) | 42, 1234567890 |
| Exactly 5 digits | 12345 |
| Negative integers | -123, -45678 |
| Any integer (positive or negative) | 42, -7 |
| Numbers with optional decimals | 1234, -56.78, .25 |
| Exactly 2 decimal places | 42.00, -3.14 |
Important Tips
Always escape regex characters twice in Java strings (e.g.,
\.to match a literal dot).Prefer non-capturing groups unless you need references.
Avoid regex for parsing structured formats like JSON, HTML, or XML — use parsers instead.
Use
Pattern.compile()once and reuse compiled patterns for better performance.Use
[\s\S]instead of.for multiline matching when DOTALL mode is needed.
Test More Regex Patterns in Java:
Want to test in a different language? Try our:
Frequently Asked Questions
How do I write a regex pattern in Java code?
How do I test if a string matches a pattern exactly?
How can I make my regex case-insensitive in Java?
How do I validate an email address using Java regex?
What is the difference between greedy and lazy quantifiers?
Does this tool use the Java regex engine?
How do I validate credit card numbers for various card types using regular expressions?
Related Articles



Test your APIs today!
Write in plain English — Qodex turns it into secure, ready-to-run tests.



