r/java • • Mar 07 '26

Build Email Address Parser (RFC 5322) with Parser Combinator, Not Regex.

A while back, I was discussing with u/Mirko_ddd, u/jebailey and u/Dagske about parser combinator API and regex.

My view was that parser combinators should and can be made so easy to use such that it should replace regex for almost all use cases (except if you need cross-language portability or user-specified regex).

And I argued that you do not need a regex builder because if you do, your code already looks like a parser combinator, with similar learning curve, except it doesn't enjoy the strong type safety, the friendly error message and the expressivity of combinators.

I've since used the Dot Parse combinator library to build a email address parser, following RFC 5322, in 20 lines of parsing and validation code (you can check out the makeParser() method in the source file).

While light-weight, it's a pretty capable parser. I've had Gemini, GPT and Claude review the RFC compliance and robustness. Except the obsolete comments and quoted local part (like the weird "this.is@my name"@gmail.com) that were deliberately left out, it's got solid coverage.

Example code:

EmailAddress address = EmailAddress.parse("J.R.R Tolkien <tolkien@lotr.org>");
assertThat(address.displayName()).isEqualTo("J.R.R Tolkien");
assertThat(address.localPart()).isEqualTo("tolkien");
assertThat(address.domain()).isEqualTo("lotr.org");

Benchmark-wise, it's slightly slower than Jakarta's hand-written parser in InternetAddress; and is about 2x faster than the equivalent regex parser (a lot of effort were put in to make sure Dot Parse is competitive against regex in raw speed).

To put it in picture, Jakarta InternetAddress spends about 700 lines to implement the tricky RFC parsing and validation (link). Of course, Jakarta offers more RFC coverage (comments, and quoted local parts). So take a grain of salt when comparing the numbers.

I'm inviting you guys to comment on the email address parser, about the API, the functionality, the RFC coverage, the practicality, performance, or at the higher level, combinator vs. regex war. Anything.

Speaking of regex, a fully RFC compliant Regex (well, except nested comments) will likely be more about 6000 characters.

This file (search for HTML5_EMAIL_PATTERN) contains a more practical regex for email address parsing (Gemini generated it). It accomplishes about 90% of what the combinator parser does. Although, much like many other regex patterns, it's subject to catastrophic backtracking if given the right type of malicious input.

It's a pretty daunting regex. Yet it can't perform the domain validation as easily done in the combinator.

You'll also have to translate the quoted display name and unescape it manually, adding to the ugliness of regex capture group extraction code.

48 Upvotes

43 comments sorted by

View all comments

Show parent comment

1

u/Mirko_ddd Mar 10 '26

I'm actually a chemical engineer by education (high school diploma, not a college degree, so not an engineer, but I don't know how to translate that into English) who entered the tech world as a hobby and currently works as a freelance Android developer (an entrepreneur, I make and distribute my own apps). So I was thinking about something chemistry-related; parsing and data mining chemical formulas from unstructured text is exactly the kind of real-world scenario where regular expressions really shine, in my opinion.

So here is the challenge: extract valid hydroxides from a chemistry textbook, while ignoring the false positives and typos.

The rules of the domain:

  1. It starts with a Metal (1 uppercase letter, optionally followed by 1 lowercase, like Na, Ca, Fe).
  2. It's followed by a hydroxide group. This can be simple (OH) or complex with parentheses and a Unicode subscript ((OH)₂, (OH)₃).
  3. We must support double-digit Unicode subscripts for massive complexes (e.g., ₁₂).
  4. The trap: We must reject typos like CaOH₂ (missing parentheses are invalid) and avoid partial matches. We also must ignore plain words like OH!.

With standard string combinators, handling Unicode ranges natively, word boundaries, and avoiding partial matches usually requires building a complex state machine or a full-blown lexer. With regex (using Sift) I can express this domain logic declaratively:

// 1. Metal element shape
var metal = exactly(1).upperCaseLetters()
        .followedBy(optional().lowerCaseLetters());

// 2. Unicode subscripts (handles double digits like ₁₂ natively!)
var subscripts = oneOrMore().range('₀', '₉');

// 3. Simple OH group (Negative Lookahead prevents partial matching on typos like CaOH₂)
var simpleOH = exactly(1).of(literal("OH"))
        .followedBy(negativeLookahead(subscripts));
        
// 4. Complex OH group (Requires parentheses and subscripts, e.g., (OH)₂)
var complexOH = exactly(1).of(literal("(OH)"))
        .followedBy(subscripts);

// 5. Final assembly: anchored to word boundaries
String hydroxideRegex = fromWordBoundary()
        .followedBy(metal)
        .followedBy(anyOf(simpleOH, complexOH))
        .shake();

When I run this against a text like: "Sodium forms NaOH, calcium forms Ca(OH)₂. Exclamations like OH! are ignored. Typos like CaOH₂ are rejected. Double digits like Xy(OH)₁₂ pass."

Regex effortlessly extracts exactly ["NaOH", "Ca(OH)₂", "Xy(OH)₁₂"].

The real killer features here are the Word Boundaries \b (to isolate the molecules from normal text) and the Negative Lookahead (?!...) (to say "only accept simple OH if there is NO subscript ahead", without actually consuming the next character).

I'd genuinely love to see how your combinator library handles the lookaround assertions and dynamic Unicode ranges without the code becoming deeply nested or requiring manual character-by-character consumption. Let me know what you think!

Actually, this use case turned out so well that I'm going to add it as a dedicated recipe in Sift's official COOKBOOK.md.

1

u/DelayLucky Mar 10 '26 edited Mar 11 '26

That is a fantastic example, Thank you!

I've been looking for these real life use cases that present a challenge to the combinator.

Basically, you'll need to compile the regex into a Pattern and use Matcher.find() loop to find each of the occurrences, correct?

Matcher matcher = hydroxidePattern.matcher(input);
while (matcher.find()) { ... }

This kind of finding-needles-in-haystack use case is where regex definitely has an edge.

The parser combinator is more like regex Matcher.matches(). It has to scan the input from the beginning.

Take for example the hydroxide, creating a parser to parse from the beginning or any fixed index is easy:

Parser<?> metal =
    one(range('A', 'Z'))
        .then(one(range('a', 'z')));
CharPredicate sub = range('₀', '₉');
Parser<?> oh = anyOf(
    string("(OH)").followedBy(consecutive(sub)),
    string("OH").notFollowedBy(sub));
Parser<String> hydroxide = metal.then(oh).source();
hydroxide.parse(input);

But again, it matches from the beginning - doesn't find the needles.

If I were to do it though, I might combine a simple regex + Substring API + the combinator to get what I need:

var metals = Substring.all(
    Pattern.compile("\\b[A-Z][a-z]"));
List<String> hydroxides = metals.match(input)
    .flatMap(m -> hydroxide.probe(input, m.index()))
    .toList();

The Substring API uses the header locator regex to find the "needles" and feeds them to the combinator in flatMap() for the more fine-grained parsing.

But it's no longer a pure "no-regex" version as I had ambitiously claimed to be able to do, lol.

On the other hand, it kinda indicates that regex. vs. combinator doesn't always have to be either-or. If you use it for the simplest scenarios like "\\b[A-Z][a-z]" that even a regex dummy like me can understand, then use combinator for the advanced, it can be sensible solution.

It would be a fair question to ask whether this is after all better than just using regex, like:

"\\b[A-Z][a-z]((OH(?![₀-₉]))|(\\(OH\\)[₀-₉]+))"

Having to read only the header pattern is obviously easier for a regex idiot like me. But to more versed regex users, my use of the header locator pattern \\b[A-Z][a-z] is perhaps not night-and-day different from the full regex?

Although, I guess the similar question applies to the Sift value proposition too: if the regex doesn't look that bad, why bother?

1

u/DelayLucky Mar 11 '26

And like a ping-pong game, here's a relatively simple case for PC: to parse the regex's character class syntax like [a-zA-Z0-9_] into a CharPredicate object that you can use to match a char.

Basically, assume CharPredicate to be a functional interface with boolean test(char);. There will be convenience methods like static CharPredicate is(char), NONE, not(), and(), or() to compose CharPredicate instances.

Specifically, the [a-zA-Z0-9_] shall be parsed as:

range('a', 'z')
    .or(range('A', 'Z'))
    .or(range('0', '9'))
    .or(is('_'));

And negative char class syntax [^abc] will be parsed as:

not(is('a').or(is('b')).or(is('c')));

This is how it's implemented using combinator (for brevity, I use CP for CharPredicate):

var chr = one(isNot(']'));
var range = sequence(
    chr.followedBy("-"), chr, CP::range);
var positiveSet =
    anyOf(range, chr.map(CP::is))
        .zeroOrMore(reducing(CP::NONE, CP::or));
var negativeSet =
    string("^").then(positiveSet).map(CP::not);
var charClass =
    negativeSet.or(positiveSet).between("[", "]");

Then for example you can use charClass.parse("[a-zA-Z-_]").

What would be a regex/Sift equivalent?

1

u/Mirko_ddd Mar 11 '26

when your goal is to parse a string directly into an Object Model/AST (like mapping syntax to CharPredicate instances), Parser Combinators are the absolute right tool for the job. Their declarative .map() capabilities are exactly what you need there.

Regex (and by extension, Sift) is inherently a Lexer. It’s string-in, string-out. It finds and extracts text incredibly fast, but it doesn't instantiate Java objects.

So, to answer your question, the Sift equivalent relies on a Mixed Approach (Lexer + Parser), which is actually very similar to the brilliant hybrid solution you suggested in your other comment.

We use Sift to safely define the extraction boundaries (the Lexer), and standard imperative Java to build the object (the Parser).

It would look something like this:

// 1. Lexer: Safely extract the components using Sift's readable DSL
String classPattern = Sift.fromStart()
    .followedBy('[')
    .capture("negation", Sift.fromAnywhere().zeroOrOne().character('^'))
    .capture("content", Sift.fromAnywhere().oneOrMore().excluding(']'))
    .followedBy(']')
    .andNothingElse()
    .shake();

// 2. Parser: Use Java to evaluate the captured "content" 
// (e.g., a while loop applying CP.range() or CP.is() based on the tokens)

But this brings us to the core philosophy of Sift. You wouldn't use Sift to write a compiler or a complex AST builder.

The real value proposition of Sift is self-documentation and maintainability for text validation and extraction. Even if a regex is as simple and universally understood as [a-zA-Z0-9_], it is still an opaque string of symbols. In Sift, writing .exactly(1).alphanumeric() makes the code instantly self-documenting. It reads like plain English (as you can omit exactly(1), since it produces no symbols).

You might not need Sift for a 10-character regex you write today. But what happens six months from now, when business requirements change, and that simple regex grows into a 150-character monster to support new edge cases?

Regex is famously a "write-only" language. Sift allows you to break that regex down into modular, testable, and reusable Java methods. It's about making sure the developer who reads the code a year from now can understand the business logic instantly, without needing a Regex cheatsheet to decipher it.

1

u/DelayLucky Mar 11 '26 edited Mar 11 '26

Lol, yeah. The capture group part of regex is always gonna be ugly.

If you use Mug Substring, it actually offers some ergonomics improvements.

For example, as shown above, the Substring.all(regexPattern).from(input) method can return all the matches in a modernized Stream, saving the need of the manual find() loop.

Another utility that might interest you: assuming you have a regex with a bunch of different capture groups.

Using Mug's Substring and its MoreCollectors, you can extract the capture groups more easily, like:

import static ...Substring.topLevelGroups;
import static ...MoreCollectors.combining;

Substring.topLevelGroups(
     compile("name: (\\w+), age: (\\d+)"))
  .from(input)
  .collect(combining((name, age) -> ...));

That said, your classPattern only peels off the [^] part. The inner content with the 3-char ranges ([a-z]) and non-range single chars ([xyz123]) aren't really lexed out, right? That's the more tricky part where it's interesting to compare regex against combinator.

1

u/Mirko_ddd Mar 12 '26

You are 100% right on both fronts.

First off, that Mug Substring API is gorgeous. Using combining(...) with standard Java Streams completely eliminates the boilerplate and potential errors of the traditional Matcher.find() while-loop. That is brilliant library design.

Secondly, you caught me! My previous example took the lazy route and only peeled the outer [^...] layer. Lexing the inner content (distinguishing between a range like a-z and a single character like x) is the tricky part where a standard regex usually becomes an unreadable mess.

To strictly lex consecutive inner tokens without skipping invalid characters, we need the \G anchor (Previous Match End), Named Capture Groups, and an OR operator. Writing \G(?:(?<start>.)-(?<end>.)|(?<single>.)) by hand is a nightmare. But with a DSL, you can compose it like Lego bricks.

Here is exactly how you would build that inner strict lexer in Sift:

Java

// 1. Define what a "Range" token looks like (e.g., "a-z", "0-9")
NamedCapture startGroup = SiftPatterns.capture("start", exactly(1).anyCharacter());
NamedCapture endGroup = SiftPatterns.capture("end", exactly(1).anyCharacter());

SiftPattern<Fragment> rangeToken = Sift.fromAnywhere()
        .namedCapture(startGroup)
        .followedBy('-')
        .then().namedCapture(endGroup);

// 2. Define what a "Single Character" token looks like (e.g., "x", "y")
NamedCapture singleGroup = SiftPatterns.capture("single", exactly(1).anyCharacter());

SiftPattern<Fragment> singleToken = Sift.fromAnywhere()
        .namedCapture(singleGroup);

// 3. Combine them into a strict inner Lexer.
// The \G anchor (fromPreviousMatchEnd) is the secret sauce here: it forces the engine 
// to match strictly from where the last match ended, preventing it from skipping invalid tokens.
String innerLexer = Sift.fromPreviousMatchEnd()
        .of(SiftPatterns.anyOf(rangeToken, singleToken))
        .shake();

Seeing your Mug example gave me an epiphany: Sift and Mug are perfectly complementary.

They solve two halves of the same problem. Sift is a write-side tool (it generates complex, self-documenting Regex Pattern instances without magic strings). Mug is a read-side tool (it consumes those Pattern instances and maps them to Objects beautifully).

Using Sift to safely generate the classPattern and innerLexer, and then passing them into Substring.topLevelGroups(...).collect(...) to build the AST would honestly be the ultimate, most ergonomic Java parsing experience without importing a heavy Compiler-Compiler framework. Thanks for sharing that!

here is the complete test I made if you are interested:

void testInnerLexerWithPreviousMatchEnd() {
    // 1. Define what a "Range" token looks like (e.g., "a-z", "0-9")
    NamedCapture startGroup = SiftPatterns.
capture
("start", 
exactly
(1).anyCharacter());
    NamedCapture endGroup = SiftPatterns.
capture
("end", 
exactly
(1).anyCharacter());

    SiftPattern<Fragment> rangeToken = Sift.
fromAnywhere
()
            .namedCapture(startGroup)
            .followedBy('-')
            .then().namedCapture(endGroup);

    // 2. Define what a "Single Character" token looks like (e.g., "x", "y")
    NamedCapture singleGroup = SiftPatterns.
capture
("single", 
exactly
(1).anyCharacter());

    SiftPattern<Fragment> singleToken = Sift.
fromAnywhere
()
            .namedCapture(singleGroup);

    // 3. Combine them into a strict inner Lexer.
    // The \G anchor (fromPreviousMatchEnd) is the secret sauce here: it forces the engine
    // to match strictly from where the last match ended, preventing it from skipping invalid tokens.
    String innerLexer = Sift.
fromPreviousMatchEnd
()
            .of(SiftPatterns.
anyOf
(rangeToken, singleToken))
            .shake();

    // Verify the engine assembled the \G anchor and the non-capturing OR operator (?: ... | ... ) correctly
    
assertEquals
("\\G(?:(?<start>.)-(?<end>.)|(?<single>.))", innerLexer);

    java.util.regex.Pattern pattern = java.util.regex.Pattern.
compile
(innerLexer);

    // Test string: a range (a-z), two singles (x, y), and another range (1-9)
    java.util.regex.Matcher matcher = pattern.matcher("a-zxy1-9");

    // Iteration 1: Should match "a-z" as a Range token
    
assertTrue
(matcher.find());
    
assertEquals
("a", matcher.group("start"));
    
assertEquals
("z", matcher.group("end"));
    
assertNull
(matcher.group("single")); // Not a single character token

    // Iteration 2: Should match "x" as a Single token (starting EXACTLY after 'z')
    
assertTrue
(matcher.find());
    
assertNull
(matcher.group("start"));
    
assertNull
(matcher.group("end"));
    
assertEquals
("x", matcher.group("single"));

    // Iteration 3: Should match "y" as a Single token
    
assertTrue
(matcher.find());
    
assertNull
(matcher.group("start"));
    
assertNull
(matcher.group("end"));
    
assertEquals
("y", matcher.group("single"));

    // Iteration 4: Should match "1-9" as a Range token
    
assertTrue
(matcher.find());
    
assertEquals
("1", matcher.group("start"));
    
assertEquals
("9", matcher.group("end"));
    
assertNull
(matcher.group("single"));

    // Iteration 5: End of string, no more valid tokens
    
assertFalse
(matcher.find());
}

1

u/Mirko_ddd Mar 12 '26

I don t know why the code of the test is formatted so badly. sorry

1

u/DelayLucky Mar 12 '26 edited Mar 12 '26

Yeah, you can definitely use them together.

One other tool that may interest you, assuming your pattern is fixed without much fine control like \\(name: (.+), time: (.+)\\) (obviously this is a bad regex that's subject to catastrophic backtracking, but the safe one is harder to write).

You could use Mug's StringFormat class:

private static final StringFormat TIME_SPEC =
    new StringFormat("(name: {name}, time: {time})");

TIME_SPEC.parse(input, (name, time) -> ...);

The syntax is quite similar to using regex + Substring. But a few differences:

  1. It's more readable.
  2. It's compile-time checked. If you used 3 lambda args, or if you messed up the parameter order and used (time, name) -> ..., compilation will fail.
  3. It's not subject to backtracking because internally it uses interleaved String.indexOf() calls, which is probably about as fast as it can be.

This works the best if you have no specific requirement of the placeholder parts. But what if you do? Say, you want the name to be a word, and you want the time to be a valid time string.

This is where you might not agree with me: I would suggest not to do the validation in regex.

Using regex can be complicated; and you get no useful error message. It's just an opaque match/no-match. You have no idea which part didn't match.

Instead, with StringFormat having located the "needles", parse - don't validate, in Java:

TIME_SPEC.parseOrThrow(
    input,
    (name, time) -> {
      checkArgument(CharPredicate.word().matchesAllOf(name), "%s isn't a word", name);
      return buildTimeSpec(name, LocalTime.parse(time));
    });

That is, again, prefer Java over regex. The code will be easier to understand and you get a meaningful stack trace with useful error message when parsing or validation fails.

If you can parse or validate in Java as easily or more easily, don't regex!