r/java • u/DelayLucky • 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.
View all comments
Show parent comment
1
u/Mirko_ddd Mar 08 '26 edited Mar 08 '26
I love the "Parse, Don't Validate" philosophy, and you make an incredibly compelling case for Dot Parse!
To answer your challenge, here is how Sift approaches those exact examples. My goal wasn't to invent a new parsing engine, but to make the underlying regex engine actually readable and safe.
- Using Sift, this remains purely structural and declarative, without needing to inject imperative lambdas like
suchThat(n -> n.length() == 5). ThematchesEntiremethod inherently enforces full-string boundaries:- Your combinator is undeniably elegant (
Parser.first("user_id=").then(Parser.word())).With Sift, using named capture groups and the native Java
Matcher:The slight advantage here is that regex character classes are universal standards. A developer doesn't need to check the library docs to know exactly what
alphanumeric()orword()includes under the hood. Plus, you can define the JavaPatternonce and execute it instantly with zero stream-allocation overhead.- The regex Gemini gave you
(?!-)(?!.*-\.)(?!.*\. -).*(?<!-)is horrific and exactly the kind of unmaintainable "regex golf" that gives regular expressions a bad name.If we strictly stay within Java, I 100% agree with your approach. Splitting the string with Mug's
Substringand using!label.startsWith("-")is clean, readable, and perfectly idiomatic. Regex isn't a silver bullet, and Sift doesn't try to replace pure Java for imperative tasks.However, the reason that Gemini's regex looks so bad is because raw lookarounds like
(?!)and(?<!)are inherently unreadable.If a developer wanted to validate the entire domain in a single pass, without loops or splitting, Sift turns that exact "black magic" into something that reads just like your Java code.
By breaking down the regex into smaller, semantic variables, developers can compose rules step-by-step. It makes the logic completely self-documenting and much easier to reason about:
It maps conceptually 1-to-1 with your
startsWithandendsWithlogic, with one structural advantage: it natively restricts the body of the string to valid domain characters. YourstartsWithendsWithcheck would accidentally allow invalid strings likemy_invalid_label!@#to pass through.Ultimately, we are totally on the same page: writing complex, raw regex by hand is a nightmare. Combinators like Dot Parse and utilities like
Substringare fantastic additions to the ecosystem. My goal with Sift is simply to ensure that when developers do reach for regex, it no longer looks like line noise.PS: sorry for not using ordinal points, for some reason they fuc*up the whole code blocks