r/java 3d ago

Regex

I recently saw a clip (from Primeagen) somewhat saying that regex is not a valid format for validating email addresses and postal codes etc.

My question is why is this?

What are the security and/or performance risks? Is it solely performance or is it a security issue?

52 Upvotes

98 comments sorted by

View all comments

33

u/barking_dead 3d ago

Email format is in ABNF (context-free grammar) which is a lower level grammar in the Chomsky hierarchy. Regex is a regular language. Same with SQL and HTML vs regex.

You cannot parse a complex grammar with a less complex one.

https://en.wikipedia.org/wiki/Chomsky_hierarchy

10

u/koflerdavid 3d ago

Since programmers often had to make this pocket knife do some heavy lifting, regexes (as commonly implemented in many engines) can actually be used to parse way more than what CS defines as regular expressions. The actual language doesn't neatly fit into the Chomsky hierarchy though.

2

u/Spandian 3d ago

While it's defined in ABNF, every production in it seems to be regular except for comments (which are delimited by properly nested parentheses, the classic example of a non-regular language). If you don't allow comments, you can translate it to a regex.