DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Software Design and Architecture
  3. Performance
  4. Making Regular Expressions Simple With VerbalExpressions

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!

Chris Berry user avatar by
Chris Berry
·
May. 24, 17 · Tutorial
Like (3)
Save
Tweet
Share
6.36K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Content delivery network

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stress Testing Tutorial: Comprehensive Guide With Best Practices
  • Practical Example of Using CSS Layer
  • Mission-Critical Cloud Modernization: Managing Coexistence With One-Way Data Sync
  • What’s New in the Latest Version of Angular V15?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: