getting startedJava
Java RegEx Tester

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.regex in several ways. Key differences to be aware of:

  • Possessive quantifiers (*+, ++, ?+) are supported in Java but not in JavaScript

  • Atomic groups ((?>...)) work in Java but not in JavaScript

  • Unicode property classes like \p{IsGreek} or \p{Sc} have broader support in Java

  • Backreference syntax differs in replacement strings: Java uses $1, JavaScript uses $1 (same), but Java also supports \1 in the pattern

  • Flags: Java supports Pattern.CANON_EQ and Pattern.UNIX_LINES which have no JS equivalent

For production Java code, always verify patterns using Pattern.compile() in your IDE or a Java runtime environment.

How to Use:

  1. Enter your regular expression.

  2. Provide a test string.

  3. 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

c.t

cat, cot, cut

\d

Any digit [0-9]

\d{3}

123, 456

\D

Any non-digit

\D+

abc, hello

\w

Word char [a-zA-Z0-9_]

\w+

hello_42

\W

Non-word character

\W

@, #, !

\s

Whitespace (space, tab, newline)

\s+

spaces, tabs

\S

Non-whitespace

\S+

hello

^

Start of string/line

^Hello

Hello at start

$

End of string/line

world$

world at end

\b

Word boundary

\bcat\b

cat (not cats)

[abc]

Character class

[aeiou]

any vowel

[^abc]

Negated class

[^0-9]

non-digit

[a-z]

Range

[a-zA-Z]

any letter

*

0 or more (greedy)

ab*c

ac, abc, abbc

+

1 or more (greedy)

ab+c

abc, abbc

?

0 or 1 (optional)

colou?r

color, colour

{n}

Exactly n times

\d{4}

2024

{n,m}

Between n and m times

\d{2,4}

12, 123, 1234

*?

0 or more (lazy)

<.*?>

shortest tag

(abc)

Capturing group

(\d+)-(\d+)

groups: 12, 34

(?:abc)

Non-capturing group

(?:ab)+

ab, abab

(?=...)

Positive lookahead

\d(?=px)

5 in 5px

(?!...)

Negative lookahead

foo(?!bar)

foo not before bar

(?<=...)

Positive lookbehind

(?<=@)\w+

domain after @

(?<!...)

Negative lookbehind

(?<!\d)px

px not after digit

\p{L}

Any Unicode letter

\p{L}+

Hello, 你好

\1

Backreference to group 1

(\w+)\s\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: ^abc matches abc only if it's at the start.

  • $: Anchors the match at the end of a line or string. Example: xyz$ matches xyz only at the end.

  • |: Acts as a logical OR operator. Example: cat|dog matches either cat or dog.

Character Classes

  • [abc]: Matches any one character: either a, b, or c.

  • [^abc]: Matches any character except a, b, or c.

  • [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*l matches ll, lol, lool, etc.

  • +: Matches one or more occurrences. Example: lo+l matches lol, lool, but not ll.

  • ?: Matches zero or one occurrence. Also makes quantifiers lazy when placed after them.

  • {n}: Matches exactly n occurrences. Example: a{3} matches aaa.

  • {n,}: Matches n or more occurrences.

  • {n,m}: Matches between n and m occurrences.

Groups and Capturing

  • (abc): Captures and groups the match for abc. Can be reused with backreferences.

  • (?:abc): Groups abc without 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\1 matches repeated words like hello 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 by px.

  • (?!...): Negative lookahead. Ensures the following characters do not match the pattern. Example: foo(?!bar) matches foo only if not followed by bar.

  • (?<=...): 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

^\d+$

Positive integers (any length)

123, 987654

^\d{1,10}$

Positive integers (max 10 digits)

42, 1234567890

^\d{5}$

Exactly 5 digits

12345

^-\d+$

Negative integers

-123, -45678

^-?\d+$

Any integer (positive or negative)

42, -7

^-?\d*.?\d+$

Numbers with optional decimals

1234, -56.78, .25

^-?\d*.\d{2}$

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?

Use Pattern.compile() and Matcher from java.util.regex to define and apply regex.

How do I test if a string matches a pattern exactly?

Use "yourString".matches("yourPattern") to check for a full match.

How can I make my regex case-insensitive in Java?

Use the (?i) flag in the pattern or Pattern.CASE_INSENSITIVE.

How do I validate an email address using Java regex?

Use the pattern ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$.

What is the difference between greedy and lazy quantifiers?

Greedy matches as much as possible; lazy matches as little as needed. Add ? after any quantifier to make it lazy (e.g., *? instead of *).

Does this tool use the Java regex engine?

This tool runs in the browser using the JavaScript regex engine, which is similar to Java but has some differences. Possessive quantifiers (*+, ++), atomic groups (?>...), and some Unicode properties (\p{IsGreek}) work in Java but not in JavaScript. Always verify critical patterns in a Java runtime.

How do I validate credit card numbers for various card types using regular expressions?

Use card-specific prefix patterns: Visa starts with 4 (13 or 16 digits), MasterCard starts with 51-55 (16 digits), AmEx starts with 34 or 37 (15 digits). Always combine regex format checking with the Luhn algorithm for real-world validation.

Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.