A pattern tested against strings

How to test a regular expression without overclaiming what it validates

A passing sample demonstrates one behavior. It does not prove that a pattern fully validates every possible input in a production system. A regular expression can match the examples you tried and still accept values you never intended, reject values you should accept, or behave differently in another engine. Testing a regular expression therefore means testing the claim you want to make about it, not only the pattern itself.

This guide shows a practical way to test a pattern: state what it should and should not accept, build a set of positive and negative cases, check edge cases and engine differences, and record the limits of what you tested. It uses small, readable examples. It does not claim that a pattern which passes these checks is safe for every security-sensitive use.

Start by writing down the claim

Before testing, write one sentence that states what the pattern is supposed to do. For example: This pattern should accept a product code made of three uppercase letters, a hyphen, and four digits, and nothing else. That sentence gives you a standard to test against. Without it, a test result is easy to misread. A match may look like success even when the input is not a valid product code, because the pattern was never asked to reject it.

Also write down what the pattern is not supposed to do. A pattern for a product code is not supposed to check whether the code exists in a database, whether it belongs to a particular customer, or whether it is spelled correctly in a human sense. Those checks belong elsewhere in the application. Writing the limits down early prevents a common overclaim: treating a pattern match as proof that the input is genuine, complete, or safe.

Finally, name the engine and flags you are testing with. JavaScript, PCRE, .NET, Python, Java, Go, and other engines differ in supported syntax, flag meanings, and details such as how a dot treats newlines or how Unicode is handled. A pattern that behaves one way in a browser tester may behave differently in a server language. Record the engine, the flags, and the version or environment when the result matters.

Test both acceptance and rejection

A useful test set has two sides. Positive cases are inputs the pattern should accept. Negative cases are inputs it should reject. Many test suites are weak because they contain only positive cases. A pattern that accepts everything will pass every positive case, so positive cases alone cannot show that the pattern is selective.

Build positive cases from realistic examples, not only the simplest one. If the pattern should accept a product code, include more than one valid code, with different letters and digits. If it should accept a name, include names of different lengths and with characters that are valid in your rules, such as a hyphen or apostrophe where your rules allow them. Each positive case should be one you would accept in real use.

Build negative cases from the mistakes and attacks you expect. Include inputs that are almost valid: one character too short, one character too long, a lowercase letter where only uppercase is allowed, a space at the start or end, a missing hyphen, an extra hyphen, or a punctuation mark in the wrong place. Include empty input. Include input that contains the valid pattern as part of a longer string, because an unanchored pattern may match a substring and report success even though the whole input is not valid.

Check the edge cases that break simple patterns

Edge cases are where many patterns fail. Test empty input, a single character, the minimum length, the maximum length, and one character beyond the maximum. Test leading and trailing spaces, tabs, and newlines. Test input with more than one line when the field could receive it. Test Unicode letters, accented characters, emoji, and characters from scripts other than Latin when your users may enter them. A pattern written with A to Z may reject a valid name that contains an accented letter, and that rejection may be a bug rather than a correct validation.

Check anchoring. A pattern without anchors can match part of a longer string. If you want the whole input to match, most engines need a start anchor and an end anchor, and you need to confirm how those anchors behave with multiline input in your engine. If you only want to find a pattern inside a larger text, anchoring to the whole string is the wrong test. State which behavior you want, then test for it directly.

Check greedy matching and capturing. A greedy quantifier can consume more than you intended, especially when the pattern is followed by more text. Test inputs where the greedy part could swallow a delimiter. If you use groups, check what each group captures, not only whether the whole pattern matches. A pattern can match while capturing the wrong part, and later code that uses the captured group will then use the wrong value.

Worked example: a product code pattern

Test string Should match
Pattern tested ^[A-Z]{3}-[0-9]{4}$
ABC-1234 Yes
XYZ-0000 Yes
QWE-9876 Yes
abc-1234 No (lowercase letters)
ABC1234 No (hyphen missing)
ABC-123 No (only three digits)
ABC-12345 No (five digits)
ABC- 1234 No (contains a space)
Empty string No
XXABC-1234YY No (code is part of a longer string)

Suppose a form accepts a product code with three uppercase letters, a hyphen, and four digits. A first draft might be the pattern ^[A-Z]{3}-[0-9]{4}$ in an engine that supports that syntax. The claim is: this pattern accepts exactly that shape and nothing else.

Start with positive cases. ABC-1234 should match. XYZ-0000 should match. QWE-9876 should match. If any of these fail, the pattern or the test setup is wrong, and you should fix the setup before trusting any other result.

Then add negative cases. abc-1234 should not match, because the letters are lowercase. ABC1234 should not match, because the hyphen is missing. ABC-123 should not match, because it has only three digits. ABC-12345 should not match, because it has five digits. ABC- 1234 should not match, because it contains a space. An empty string should not match. The string XXABC-1234YY should not match, because the code is part of a longer string. The string ABC-1234 followed by a newline or extra text should not match unless your rules explicitly allow trailing input.

Then add edge cases. Test ABC-1234 with a leading space and with a trailing space. Test a code with a lowercase letter in one position and uppercase in the others. Test a code with a Unicode letter that looks like a Latin letter but is a different character. Test the pattern in the engine you will actually use, with the same flags. If your application trims spaces before validation, test the pattern on the trimmed value and test the trimming step separately. Do not let the tester hide a step the application performs.

Record the results in plain language. For example: Tested in JavaScript with no flags. Accepted the three valid codes. Rejected the twelve invalid cases listed above. Did not test codes with accented letters, because the rule allows only A to Z. That record is more useful than saying the pattern is validated. It tells the next reader exactly what was checked and what was left out.

Watch for performance and safety problems

Some patterns can be very slow on certain inputs. Nested quantifiers and overlapping alternatives can cause a pattern to take far longer on a long or repetitive string than on a short one. This is sometimes called catastrophic backtracking. Test with long inputs, repeated characters, and near-miss inputs that almost match but fail at the last character. If a pattern is slow on a plausible input, simplify it, add a length check before applying it, or use a parser for that part of the task.

Do not rely on a regular expression alone to make untrusted input safe. A pattern can check shape, but it cannot by itself prove that a value is harmless in a database query, a shell command, a file path, or HTML output. Those contexts need their own escaping, parameterisation, or encoding. A pattern that rejects many dangerous characters may still allow a value that is unsafe in a particular context, and a pattern that allows only a narrow set of characters may still be the wrong control if the dangerous input arrives through another field.

For security-sensitive validation, combine a readable parser and explicit application rules with the regular expression. Check length first. Check the allowed character set. Check structure with the pattern. Then apply the checks that belong to the domain, such as verifying that a code exists, that a date is real, or that a value is within an allowed range. Keep each check simple enough that a reviewer can follow it without decoding a long pattern.

Test in the real environment, not only in a tester

A browser tester is useful for exploring a pattern and for sharing examples. It is not the same as testing in the application. The application may trim input, change line endings, decode entities, normalise Unicode, or apply the pattern with different flags. Test the pattern with the same input pipeline the application uses, including any cleaning steps that run before or after the pattern.

Test with realistic data, not only hand-picked cases. If you have a set of past inputs, run the new pattern against them and compare the results with the old behavior. Look at the inputs that change from accepted to rejected and from rejected to accepted. For each changed input, decide whether the new result is correct. A pattern that fixes one case and breaks ten real cases is not an improvement, even if it passes a small hand-written suite.

Keep the test cases with the pattern. A pattern without its test cases is hard to review and easy to break. Store the pattern, the engine and flags, the positive cases, the negative cases, and a short note about the limits. When someone changes the pattern later, they can rerun the same cases and see what changed. That habit matters more than any single clever pattern.

Limitations

Testing can increase confidence, but it cannot prove that a pattern is correct for every possible input. The set of possible inputs is usually too large to test exhaustively. A test suite shows that the pattern behaved as expected on the cases you chose. It does not show that it will behave the same way on cases you did not think of, in an engine you did not test, or after a change in the surrounding code.

A tester also cannot tell you whether your rule itself is right. If the rule says that only A to Z letters are allowed, the tester can check that rule. It cannot tell you whether that rule is fair, complete, or appropriate for your users. That judgment comes from the requirements, not from the pattern. Likewise, a pattern that matches a common email shape does not prove that an address exists, belongs to the person who entered it, or can receive mail. Do not present a pattern match as proof of identity, ownership, or deliverability.

Use the related tool carefully

This guide is paired with a browser-only utility. The tool is a practical aid for small examples and inspection; it is not a substitute for application testing, a formal data pipeline, or professional review where the decision has higher consequences.

Open the related Regular Expression Tester

Related tools in this category

Frequently asked questions

Does a matching test prove my pattern validates the input?

No. A match proves that the pattern matched that input in that engine with those flags. It does not prove that the pattern rejects everything else, that the rule is correct, or that the input is genuine or safe. State the claim, test both acceptance and rejection, and record the limits.

How many test cases are enough?

Enough to cover the rule you wrote. Include valid examples, near-miss invalid examples, empty input, boundary lengths, whitespace, multiline input, and Unicode cases when they matter. If you cannot name a negative case, you may not yet know what the pattern is supposed to reject.

Why does the same pattern behave differently in another language?

Regular expression dialects differ. Engines differ in supported syntax, flag meanings, Unicode handling, and how anchors and newlines behave. Test in the engine you will actually use, with the same flags, and record the engine in your notes.

Should I use a regular expression to validate email addresses?

A pattern can check that an address has a plausible shape, but it cannot prove that the address exists or belongs to the person who entered it. For important flows, use a simple shape check plus a confirmation step, such as sending a verification message, rather than relying on a long pattern alone.

Sources