CodeX
Published in

CodeX

Regex: The Simple Edition

Regex, also known as a regular expression, are patterns used throughout various programming languages that match parts of a primitive data type known as strings. If you thought patterns were already hard enough to find outside of code, you are now in for a rude awakening. But don’t worry, that’s why you are here; to learn the basics of a complex topic. But let me remind you, this is a simplified version of regex. This means you’ll have to continue reading up on this topic, but don’t worry because one place that is good to continue learning about regular expressions is freeCodeCamp.org. Anyway, let us begin your journey.

Introduction

A mathematician named Ken Thompson created regular expression in 1986. He drew inspiration from Stephen Kleene, Waren S. McCulloh, and Walter Pitts. Though regex may seem like a simple concept, it has several key parts that must be learned to harness its power. Within this article, we’ll only be addressing five parts: character classes, anchors, quantifiers, and alternation. For this article, the programming language being used is JavaScript.

Hold Up!

I forgot to mention the most crucial part, the structure of regex and how to even use said pattern. To begin a pattern, you must first create the pattern. You do this with two forward slashes like this / /. We know this as the search pattern. To find an exact match, you will just put a string in between the search pattern like so /Jason/. By default, it will only find the first match of Jason. However, you can change the behavior of the search pattern through flags. We will use two types of flags, -g and -i. By doing /Jason/g, the search pattern will now look through multiple entries of Jason within a string.

let string = 'Jason Padilla';
let literalMatch = /Jason/g;

const test = literalMatch.test(string);
const match = string.match(literalMatch);

console.log(test) // true
console.log(match) // [‘Jason’]

Now add -i to the search pattern: /Jason/gi. This search pattern is no longer case-sensitive, meaning whether the string has Jason like JASON or jAson, the pattern will still match it.

let string = 'Jason jAson JASON';
let regex = /Jason/g;

const match = string.match(regex);

console.log(match) // [‘Jason’]



let string = 'Jason jAson JASON';
let regex = /Jason/gi;

const match = string.match(regex);

console.log(match) // [‘Jason’, ‘jAson’, ‘JASON’]

There are more special characters to be talked about, but the show must go on. And to continue this show, you must see if regular expression even works. We can do this with the .test() method. This method takes the regex, applies it to a string, and returns true or false depending on whether a match was found or not. There’s another method known as .match() that creates a new array, extracts the match/s, and pushes them within that new array. Now let’s begin.

Character Classes

Foremost, character classes are simple, it allows the computer to distinguish between characters. An example of this can discern between letters and numbers or only numbers. To match only numbers, you will type into the search pattern /\d/g, with the addition of the -g flag to enable iteration.

let numbers = "1234567890";
let regex = /\d/g;

const match = numbers.match(regex);

console.log(match) // [‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘0’]

To match letters and numbers, you’ll enter \w into the search pattern to match any character (alphanumeric and underscore).

let numbers = "A B C, It's easy as 123";
let regex = /\w/g;

const match = numbers.match(regex);

console.log(match) // ['A', 'B', 'C', 'I', 't', 's', 'e', 'a', 's', 'y', 'a', 's', '1', '2', '3']

You can also do the opposite with the capitalized variation; \D matches everything that’s not a digit, while \S matches everything except for white space, line breaks, and tabs.

let numbers = "A B C, It's easy as 123";
let regex = /\D/g;

const match = numbers.match(regex);

console.log(match) // ['A', ' ', 'B', ' ', 'C', ',', ' ', 'I', 't', "'", 's', ' ', 'e', 'a', 's', 'y', ' ', 'a', 's', ' ']



let numbers = "A B C, It's easy as 123";
let regex = /\S/g;

const match = numbers.match(regex);

console.log(match) // ['A', 'B', 'C', ',', 'I', 't', "'", 's', 'e', 'a', 's', 'y', 'a', 's', '1', '2', '3']

Another cool thing about character class is the square brackets []. This allows you to search through a specific group of characters that you want to match. To enhance this further, you can define a range of characters you want to match through the use of hyphens -. We can see an example of this below. In this example, I want to match all characters that end with at. This is done by defining a range of all the alphabetical characters thro [a-z] and adding `at` at the end as the exact match of the end characters we want.

let numbers = "That rat ran with my food. So I tried to hit it with a bat. Afterwards I laid on the mat while he ate the food on my doormat";

let regex = /[a-z]at/g;

const match = numbers.match(regex);

console.log(match) // ['hat', 'rat', 'bat', 'mat', 'mat']

Anchors

Anchors are special in regular expressions, as they don’t match specific characters; they match the position of a character. ^ anchor matches the position of the character at the beginning of the text. $ anchor matches the position of the character at the end of the text.

let numbers = "The story never ends, it just has new beginning";
let regex = /^The/g;

const match = numbers.match(regex);

console.log(match) // ['The']



let numbers = "The story never ends, it just has new beginning";
let regex = /beginning$/g;

const match = numbers.match(regex);

console.log(match) // ['beginning']

Quantifiers & Alternation

Quantifiers specify the number of characters that need to be matched within a string. For this section, we will only talk about quantity specifiers through the use of curly brackets {}. Curly brackets have two parts, the lower and upper numbers. Alternation takes after the logical OR operator | that matches one string or another.

let numbers = "abcdefghijklmnopqrstuvwxyz";
let regex = /[a-z]{10}/g;

const match = numbers.match(regex);

console.log(match) // ['abcdefghij', 'klmnopqrst']



let numbers = "Here at Marcy Lab, we do both frontend and backend development";
let literalMatch = /frontend|backend/g;

const match = numbers.match(literalMatch);

console.log(match) // ['frontend', 'backend']

Close Out

Regular expression is not an easy topic to learn at all. There are many components of regex that I particularly left out because those dive deep into the capabilities of regular expression; some of them being positive/negative look-around, capturing groups, etc. Remember, this article is a simple overview of regex, so it will be in your best interest to continue learning on other platforms. Some resources I recommend are freeCodeCamp (where I drew inspiration from), Odin Project, MDN, and so on. Remember, coding is a skill that is learned through countless hours of studying and work; so do not feel discouraged when times or the topic at hand get tough. Keep moving forward and thank you for taking the time to read my article.

--

--

--

Everything connected with Tech & Code. Follow to join our 900K+ monthly readers

Recommended from Medium

Great Practices When Programming in JavaScript.

Basic JavaScript Code for Live Conversational AI With Its WebSocket’s API

Let’s create a Cookie Clicker with RxJS

RxJS How To? Understand difference between *Time operators

Routing 101 in ExpressJS

React Component Libraries

Binary search and two pointer

Styling your console in Javascript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jason Padilla

Jason Padilla

Software Engineer in Training. Currently attending Marcy Lab School

More from Medium

Decoding Coding 1.0 | Why learn to code?

Basic things to know about “Application Framework”

Create application using VB.NET in Visual Studio 2022

How to Write Ternaries That Will Make Cartoon Heart Eyes Pulsate in and Out of Your Dev Team’s Eye…