Regex is a very powerful tool, but its terse and cryptic vocabulary can make constructing and communicating them with others a challenge. Even developers who understand them well can have trouble reading their own back just a few months later! I am not good at Regex. During the seven years of my software engineer, I have never written a regex from scratch. I tried learning it a few times, seriously. But gradually, my regex memory is faded away.
Recently, I saw this awesome library super-expressive and I immediately love it. It provides a programmatic and human-readable way to create regular expressions. Its API uses the fluent builder pattern and is completely immutable. It’s built to be discoverable and predictable:
- Properties and methods describe what they do in plain English
- Order matters! quantifiers are specified before the thing they change, just like in English (e.g.
- If you make a mistake, you’ll know how to fix it. SuperExpressive will guide you towards a fix if your expression is invalid
- Sub-expressions can be used to create meaningful, reusable components
- Includes an
index.d.tsfile for full TypeScript support
SuperExpressive turns those complex and unweildy regexes that appear in code reviews into something that can be read, understood, and properly reviewed by your peers - and maintained by anyone!
Quoted from the library README
npm i super-expressive
const SuperExpressive = require("super-expressive"); // Or as an ES6 module import SuperExpressive from "super-expressive";
The following example recognizes the HTTP protocol or some added string inside the list of URLs.
const SuperExpressive = require("super-expressive"); const httpRegex = SuperExpressive() .allowMultipleMatches .anyOf .string("http") .string("nartc") .string("jira") .end() .toRegex(); // Produces the following regular expression: /(?:http|nartc|jira)/g;
You can immediately use the
httpRegex variable to test against your input string and that’s it. The code is much more readable and maintainable.
It is just a simple example, usually regex will be much more complex. You can check the full list of the API
If you need a regex for validation purposes on Angular and you don’t want to install super-expressive, that’s fine. My friend @nartc built a playground online where you can simply generate your regex using super-expressive syntax and test your result as well.
Check out the working app -> https://sepg.netlify.app/
I contributed to the responsiveness of the application on the mobile web browser.
If you like it, give a star to my friend repo yeah! 💪💪💪