Everyone knows regex is most powerful feature of JavaScript but at the same time it can give hard time to even experienced developers. Reading your regex after few months sometime become too difficult. In today article we will gonna learn how we can write regex in natural language.
Super expressive
Two days ago a new game changing library came into reality. This is a JavaScript library that allows you to build regular expressions in almost natural language – with no extra dependencies, and a lightweight code footprint (less than 3kb with minification + gzip!).
On first place why we need a new library for regex. The answer is simple even the regex is so powerful but writing syntax of regex is too complicated. Most of the time we again need to read the docs of regex to create a new regex.
This library solves the issue of complex syntax. It uses the normal natural language words to create a regex.
Installation
Like any other npm package you can install this library using npm or yarn.
npm i super-expressive --save
Usage
To use this library first of all you need to import this library.
const SuperExpressive = require('super-expressive');
Example
Find Mutiple hello in a string.
SuperExpressive()
.allowMultipleMatches
.string('hello')
.toRegex();
// ->
/hello/g
Find CaseInsenstive Hello.
SuperExpressive()
.caseInsensitive
.string('HELLO')
.toRegex();
// ->
/HELLO/i
Captures the value of a 16-bit hexadecmal number like 0xC0D3
const SuperExpressive = require('super-expressive');
const myRegex = SuperExpressive()
.startOfInput
.optional.string('0x')
.capture
.exactly(4).anyOf
.range('A', 'F')
.range('a', 'f')
.range('0', '9')
.end()
.end()
.endOfInput
.toRegex();
// Produces the following regular expression:
/^(?:0x)?([A-Fa-f0-9]{4})$/
Similarly you can create any regex in natural language using this library. I hope you have learned how to write regex in natural language.
How to check an element is in viewport using Intersection Observer API
I don't think this really removes the challenges of reading a regular expression. If you're already familiar with regex the is some benefits for things like the non-capturing group.
But when you need to go back and modify a regex it is more nuanced than just "I don't remember what
(?:
is" all of the tool to check your regex against inputs can be thrown out when using this syntax.Most of what I have to say were addressed by Adam and DGM, but I don't think they cover your second point very well.
"how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?"
I…