Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Making Regular Expressions Simple With VerbalExpressions

DZone's Guide to

Making Regular Expressions Simple With VerbalExpressions

Complicated regular expressions can be hard to read and maintain, but luckily, with the help of VerbalExpressions, it's no longer the case!

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

Quick, someone tell me what this regular expression is doing:

(?:\()?[0-9]{3}(?:\))?(?: )?(?:\.)?[0-9]{3}(?:-)?(?:\.)?[0-9]{4}


It’s hard, isn’t it? Regular expressions are not the easiest thing in the world to quickly understand. Most developers only work with regular expressions when they really, really have to.

And even then, many will go and Google a site where you can quickly grab an expression that might be close to what they want to do. Or they will try to write an expression using a cheat sheet hoping that they understand the syntax for what they’re attempting to do. And then, after much trial and error, they will have a hacked together expression in their code that they hope they’ll never have to come back to.

But what if there was another way?

There is, and it’s called VerbalExpressions. VerbalExpressions is a collection of over two dozen repositories and libraries that use plain and simple language to describe a regular expression. In fact, the motto they use is, “Regular Expressions made easy.”

VerbalExpressions is a quick and easy way to write complex regular expressions. In this blog, I will use the VerbalExpressions JavaScript implementation as my library of choice to demonstrate this great tool to you.

The Demo

First, VerbalExpressions can be used either in the browser using a standard script tag.

<script src="VerbalExpressions.js"></script>


Or, it can be used from a Content Delivery Network such as jsDelivr CDN.

My choice was to use it on the server using Node.js and install it locally using NPM.

npm install verbal-expressions


Using VSCode, I created a file that I will call phonecheck.js. From here, I can start using VerbalExpressions to write a module that will check different types of phone numbers.

var VerbalExpressions = require('verbal-expressions');

var phoneExp = VerbalExpressions() 
               .startOfLine()
               .maybe("(")
               .range('0', '9')
               .repeatPrevious(3)
               .maybe(")")
               .maybe(" ")
               .maybe(".")
               .range('0', '9')
               .repeatPrevious(3)
               .maybe("-")
               .maybe(".")
               .range('0', '9')
               .repeatPrevious(4)
               .endOfLine();

var phonenumber = {
   standard: "(123) 456-7890",
   invalid: "(123) 456-789",
   withdots: '123.456.7890'
}

// Use RegExp object's native test() function
if (phoneExp.test(phonenumber.invalid)) {
   console.log('The phone number is valid.'); // This output will fire}
} else {
   console.log('The phone number is invalid.');
}
console.log(phoneExp._source);


The code is quite simple and is actually very easy to read. You first import VerbalExpressions as you would any other node module. Then we create our expression by first calling the VerbalExpressions constructor and chaining together each option that we would like to check against.

Notice that we have a startOfLine function and an endOfLine function which is the actual container for the generated regular expression. We can then go on asking maybe, range, repeat using the library’s chainable options.

At the end of this, we now have a human-readable expression to check a 10-digit phone number for parens around the area code, dots or dashes between the number groups, and that the phone number actually does have 10 digits broken up in the correct blocks.

Testing Our Solution

So how do we test that our expression really does work? We made up an object literal that contains our three test case phone numbers

  • One with the standard area code with 10 digits.

  • One that will be short one number.

  • One that we replace the dashes between the number groups with dots.

Our VerbalExpressions function result has a built-in test function which we can simply pass our phone number into and which will return a boolean.

As an added bonus, and just to demonstrate that we really are using regular expressions behind the scenes, I’ve added a console log to show the actual expression used.

phoneExp._source


If you run the code above, you’ll notice that it’s the exact same regular expression we opened up with.

String Replacement Interface

Now VerbalExpressions is really good at making regular expressions simple. But that’s not all it can do. The library also has a pretty good string replacement interface, which I will now show you.

console.log('/**************** STRING REPLACEMENT ********************/');
var sentence ='We have a red house';
var result = VerbalExpressions().find('red').replace(sentence, 'blue');

console.log('Before: ', sentence);
// Outputs "We have a blue house"
console.log( 'After: ', result);


Taking a complete sentence, you can simply create another VerbalExpression function result, call its Find function, and pass in the string you wish to replace. Chain on the replace function and pass in the replacement string. Calling the result of the VerbalExpression function will now give you a modified string complete with your new string in place.

Final Thoughts

To learn more on how VerbalExpressions works and what expressions can be created, you can visit its API documentation page on GitHub.

Regular expressions are difficult and easily error prone; most people dread writing them or modifying them.

Using VerbalExpressions can ease that pain, and actually make writing expressions fun again. Take a look through the many language implementations offered, choose your flavor and see if you too can have fun writing VerbalExpressions.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
nodejs ,verbalexpressions ,regular expressions ,web dev ,tutorial

Published at DZone with permission of Chris Berry, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}