Quick revision
The short answer
A shared validation library should hand teams named validators, such as isValidOrderId(), backed by patterns compiled once as constants, never raw regex strings to copy around. Every pattern is reviewed for nested quantifiers and overlapping alternatives and tested with long near-miss input, every input is length-checked before matching, structured formats such as emails, URLs and dates are handled by real parsers, and user-supplied patterns are never run in shared services, or only in a linear-time engine with strict limits away from the request thread.
What to remember
In this answer, we designed regex rules for a shared validation library. Teams call named validators backed by patterns compiled once as private constants. Every pattern is reviewed for nested and overlapping quantifiers and tested with long near-miss input under a time limit, every input is length-checked first, structured formats go to real parsers such as java.time and URI, and user-supplied patterns are kept out of shared services or confined to a linear-time engine with limits.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A shared validation library should hand teams named validators, such as isValidOrderId(), backed by patterns compiled once as constants, never raw regex strings to copy around. Every pattern is reviewed for nested quantifiers and overlapping alternatives and tested with long near-miss input, every input is length-checked before matching, structured formats such as emails, URLs and dates are handled by real parsers, and user-supplied patterns are never run in shared services, or only in a linear-time engine with strict limits away from the request thread.
Why this question is asked
When many teams validate the same kinds of input, each one usually writes its own regular expression, and the copies drift apart: one service accepts an email address another rejects, one pattern is slow, and one pattern can be pushed into catastrophic backtracking by a single request. A shared library is the place to fix this once. Interviewers ask this design question to see whether we treat regular expressions as code with performance and security risks, and whether we can turn that into rules other teams will actually follow. In this answer, we will look at what goes wrong without rules, then go through five rules for the library, the reasoning behind each, and how to keep them enforced over time.
1What Goes Wrong When Every Team Writes Its Own Pattern
Regular expressions are small programs, and they fail in three ways that matter in a shared setting. They can be slow: the JDK engine backtracks, and an ambiguous pattern can take exponential time on input that almost matches, which lets one request pin a CPU core. They can be wrong: a pattern for an email address or a date that looks right will usually accept some invalid values and reject some valid ones. And they can be inconsistent: when ten services each copy a slightly different pattern, a customer can sign up in one place and be rejected in another.
A shared library fixes all three only if it controls the patterns itself. If it simply exports regex strings, teams will still combine them, recompile them and pass user input into them without limits. So the design starts with the shape of the API.
2Rule 1: Expose Named Validators, Compiled Once
Teams should call a method that states the business meaning, and the pattern should stay a private detail of the library. That gives us one place to fix a bug, one place to add a length limit and one place to measure.
Notice the private static final Pattern. Compiling a pattern is expensive compared with matching, and String.matches() compiles a fresh one on each call, so hot code that uses it wastes time and memory. A compiled Pattern is immutable and safe to share between threads, while a Matcher holds the state of one match and must not be shared, which is why we create a new Matcher inside the method. We can also back these methods with Bean Validation annotations, such as a custom @OrderId constraint, so Spring controllers use the same rule.
3Rule 2: Review Every Pattern and Test It With Near Misses
Before a pattern enters the library, a reviewer looks for the shapes that cause catastrophic backtracking. The main one is a quantifier inside a quantified group where the inner part can match the same text in more than one way, such as (\w+\s?)* or (a+)+. The second is alternation whose options overlap, such as (\d|\d\d)*, because the engine can reach the same position along many paths. When we find one, we rewrite it so each input has only one way to match, or we make the group atomic with (?>...).
Review is not enough on its own, so every validator gets a test with hostile input: a long string that is valid up to the last character. JUnit 5 can fail the test if matching takes too long.
The near miss matters because a failing match is the slow case: success stops at the first path that works, failure must try them all. Static analysis helps too; tools such as SonarQube include rules that flag regexes likely to backtrack badly, and we run them on the library in CI.
4Rule 3: Check the Length Before the Pattern Runs
Every validator has a maximum length, and it checks that length before matching. This one line is the strongest protection we have, because even a pattern we failed to spot as dangerous cannot do much harm on 100 characters. It also keeps memory use predictable. The maximum comes from the domain, such as 254 characters for an email address or 20 for an order id, not from a guess, and it is part of the validator's documented contract. At the edges of the system we also cap the size of request bodies and headers, so that huge values are refused before they reach any code at all.
5Rule 4: Use Real Parsers for Structured Formats
Some formats look like a job for a regex and are not. A full email address grammar, URLs with their many parts, dates with month lengths and leap years: a pattern for these is either wrong or unreadable. The JDK and a few libraries already contain tested parsers, so the library wraps those instead.
| Input | Use | Why not a regex |
|---|---|---|
| Order ids, codes, slugs | Simple anchored pattern + length limit | A regex is the right tool here |
| Dates and times | java.time parse methods | Month lengths and leap years |
| URLs | java.net.URI or UriComponentsBuilder | Many parts and encodings |
| Email addresses | Simple check, then a confirmation mail | The full grammar is huge |
| UUIDs, numbers | UUID.fromString, Long.parseLong | Parsers return typed values |
For email addresses, the practical rule is a simple, safe check (one @, a dot in the domain, a length limit) followed by a confirmation email, because the only proof that an address works is that mail reaches it. The parsers also give us structured values, a LocalDate or a URI, instead of a string we have to pick apart again later.
6Rule 5: No User-Supplied Patterns in Shared Services
If a team lets users type a pattern, for example in a search filter or a routing rule, the user is now writing code that runs on our CPU. The rule for the library is simple: it does not accept patterns as input. Where a product really needs it, the team must use a linear-time engine such as RE2/J, which cannot backtrack catastrophically, and must still limit pattern and input length. If the JDK engine is unavoidable, the match runs on a separate bounded thread pool with a deadline that is checked inside the match, for example through a CharSequence wrapper whose charAt() throws once time is up, because Matcher ignores thread interrupts.
- Team requests a validatorwith examples of valid and invalid input
- Is there a real parser for this format?YesWrap the parserNoWrite an anchored pattern
- Review for nested or overlapping quantifiersrewrite or make atomic
- Add a length limit and near-miss testsfail if slower than 50 ms
- Release as a named methodteams never see the pattern
5 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Why not offer a generic validate(String input, String regex) method for flexibility?
Because it moves every risk back to the callers. They would pass a different regex string each time, so we could not review the patterns, we would compile on every call unless we added a cache, and some team would eventually pass in a pattern built from user input. A small set of named validators is less flexible on purpose: when a team needs a new rule, it asks for a new validator, which goes through the review and tests once and then serves everyone.
Is a compiled Pattern safe to share between threads?
Yes. Pattern instances are immutable and the JDK documents them as safe for use by multiple concurrent threads. Matcher instances are not, because they hold the position and groups of one match in progress. So we keep the Pattern in a static final field and call pattern.matcher(input) each time, which creates a cheap new Matcher for that call.
How do you change a validator without breaking teams that depend on it?
We treat validators like any public API. A change that accepts more input is usually safe, while a change that rejects input that was accepted before can break existing data, so we add a new method or a new version, publish release notes, and give teams time to move. Tests in the library include the examples that motivated each rule, so a later change cannot silently undo an earlier decision.
8Conclusion
In this answer, we designed regex rules for a shared validation library. Teams call named validators backed by patterns compiled once as private constants. Every pattern is reviewed for nested and overlapping quantifiers and tested with long near-miss input under a time limit, every input is length-checked first, structured formats go to real parsers such as java.time and URI, and user-supplied patterns are kept out of shared services or confined to a linear-time engine with limits.
Open with
I would treat regular expressions as code with a performance and security risk, and make the library the only place they live. First, teams get named validators, like isValidOrderId, and the pattern is a private static final constant, compiled once; Pattern is thread-safe, and we avoid String.matches because it recompiles every call.
Then, if they want more
Second, every pattern is reviewed for nested quantifiers and overlapping alternatives, which are what cause catastrophic backtracking, and each validator has a test with a long near-miss input, valid until the last character, that must finish within something like 50 milliseconds. Static analysis rules for regex denial of service run in CI too.
Third, every validator checks a maximum length before matching, taken from the domain, because that bounds the worst case even for a pattern we got wrong. Fourth, structured formats do not get regexes at all: dates go through java.time, URLs through URI or UriComponentsBuilder, UUIDs through UUID.fromString, and emails get a simple check plus a confirmation mail.
Fifth, the library never accepts patterns as parameters, and a shared service must not run user-supplied patterns; if a product truly needs them, it uses a linear engine like RE2/J with length limits, or a separate pool with a deadline checked inside the match.
New validators come in through a short request with examples, so the rules apply to every addition.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- JUnit 5
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You are designing a shared input validation library for many teams. What rules do you...": https://scrivio-interview-library.netlify.app/java/strings/051039cc63/