A Regular Expression is a syntax that allows you to match strings with specific patterns. Think of it as a suped-up text search shortcut, but a regular expression adds the ability to use quantifiers, pattern collections, special characters, and capture groups to create extremely advanced search patterns.


Regular Expressions (Regex) can be used any time you need to query string data, such as:

  • Analyzing command line output
  • Parsing user input
  • Examining server or program logs
  • Handling text files with a consistent syntax, like a CSV
  • Reading configuration files
  • Searching and refactoring code

Regular Expression looks like this:


Regex: Test

String: Testing the statement

Match: 1 Found


In the above "Test" term is searched in the String and one match is found. There is more thing to remember this is case sensitive. 


Let's take another example but a little more complex,


Regex:  ^(?:\d{3}-){2}\d{4}$

String: 

555-555-5555

abc-xyz-orad

Match: 2 Found


Here's a regex that matches 3 numbers, followed by a "-", followed by 3 numbers, followed by another "-", and finally ended by 4 numbers.

You can also write above ^(?:\d{3}-){2}\d{4}$ Regex as ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ You can write regex in different ways to do the same work.


How to read and write Regular Expression(regexes)


Here is a list of all quantifiers:

  • a|b - Match either "a" or "b
  • ? - Zero or one
  • + - one or more
  • * - zero or more
  • {N} - Exactly N number of times (where N is a number)
  • {N,} - N or more number of times (where N is a number)
  • {N,M} - Between N and M number of times (where N and M are numbers and N < M)
  • *? - Zero or more, but stop after first match


For example, the following regex:


coding|programing


Matches both the strings coding and programing


Meanwhile,


Hey?


Will check "y" zero or once, so this will match with "He" and "Hey" both.


For,

Hello{1,3}


Will going to match "Hello", "Helloo", "Hellooo" but not "Helloooo" As "o" letter can come 1 to 3 times only.


These can be combined like,

He?llo{2}


Will match with "Helloo" and "Hlloo", as "e" can come zero or once and "o" will be 2 times.


Greedy matching


One of the regex quantifiers we touched on in the previous list was the + symbol. This symbol matches one or more characters. This means that:


Hi+


Will match everything from "Hi" to "Hiiiiiiiiiiiiiiii". This is because all quantifiers are considered "greedy" by default.

  However, if you change it to be "lazy" using a question mark symbol (?) to the following, the behavior changes.


Hi+?


Now, the i matcher will try to match as few times as possible. Since the + icon means "one or more", it will only match one "i". This means that if we input the string "Hiiiiiiiiiii", only "Hi" will be matched.


While this isn't particularly useful on its own, when combined with broader matches like the the . symbol, it becomes extremely important as we'll cover in the next section. The . symbol is used in regex to find "any character".


Now if you use:


H.*llo


You can match everything from "Hillo" to "Hello" to "Hellollollo".


However, what if you want to only match "Hello" from the final example?

Well, simply make the search lazy with a ? and it'll work as we want:


H.*?llo


Pattern collections


Pattern collections allow you to search for a collection of characters to match against. For example, using the following regex:


My favorite vowel is [aeiou]


You could match the following strings:


My favorite vowel is a

My favorite vowel is e

My favorite vowel is i

My favorite vowel is o

My favorite vowel is u


But nothing else.


Here's a list of the most common pattern collections:


  • [A-Z] - Match any uppercase character from "A" to "Z"
  • [a-z] - Match any lowercase character from "a" to "z"
  • [0-9] - Match any number
  • [asdf] - Match any character that's either "a", "s", "d", or "f"
  • [^asdf] - Match any character that's not any of the following: "a", "s", "d", or "f"


You can even combine these together:


  • [0-9A-Z] - Match any character that's either a number or a capital letter from "A" to "Z"
  • [^a-z] - Match any non-lowercase letter


General tokens

Not every character is so easily identifiable. While keys like "a" to "z" make sense to match using regex, what about the newline character?

The "newline" character is the character that you input whenever you press "Enter" to add a new line.


Here is the list of general tokens:


  • . - Any character
  • \n - Newline character
  • \t - Tab character
  • \s - Any whitespace character (including \t, \n and a few others)
  • \S - Any non-whitespace character
  • \w - Any word character (Uppercase and lowercase Latin alphabet, numbers 0-9, and _)
  • \W - Any non-word character (the inverse of the \w token)
  • \b - Word boundary: The boundaries between \w and \W, but matches in-between characters
  • \B - Non-word boundary: The inverse of \b
  • ^ - The start of a line
  • $ - The end of a line
  • \\- The literal character "\"


So if you wanted to remove every character that starts a new word you could use something like the following regex:


\s.


And replace the results with an empty string. Doing this, the following:


Hello world how are you


Becomes:


Helloorldowreou


Combining with collections


These tokens aren't just useful on their own, though! Let's say that we want to remove any uppercase letter or whitespace character. Sure, we could write


[A-Z]|\s


But we can actually merge these together and place our \s token into the collection:


[A-Z\s]


Hello World how are you


Becomes:


Helloorldhowareyou


Word boundaries


In our list of tokens, we mentioned \b to match word boundaries. How it acts a bit differently from others.


Given a string like "This is a string", you might expect the whitespace characters to be matched – however, this isn't the case. Instead, it matches between the letters and the whitespace:





This can be tricky to get your head around, but it's unusual to simply match against a word boundary. Instead, you might have something like the following to match full words:


\b\w+\b



You can interpret that regex statement like this: "A word boundary. 

Then, one or more 'word' characters. Finally, another word boundary".


Start and end line


Two more tokens that we touched on are ^ and $. These mark off the start of a line and end of a line, respectively.


So, if you want to find the first word, you might do something like this:


^\w+


To match one or more "word" characters, but only immediately after the line starts. Remember, a "word" character is any character that's an uppercase or lowercase Latin alphabet letters, numbers 0-9, and _.



Likewise, if you want to find the last word your regex might look something like this:


\w+$


However, just because these tokens typically end a line doesn't mean that they can't have characters after them.


For example, what if we wanted to find every whitespace character between newlines to act as a basic JavaScript minifier?

Well, we can say "Find all whitespace characters after the end of a line" using the following regex:


$\s+




Character escaping


While tokens are super helpful, they can introduce some complexity when trying to match strings that actually contain tokens. For example, say you have the following string in a blog post:


"The newline character is '\n'"


Or want to find every instance of this blog post's usage of the "\n" string. Well, you can escape characters using \. This means that your regex might look something like this:


\\n


How to use a Regular Expression(Regex) ?


Regular expressions aren't simply useful for finding strings, however. You're also able to use them in other methods to help modify or otherwise work with strings.


Let's use javascript for regular expression,


Creating and searching using regex

First, let's look at how regex strings are constructed.


In JavaScript (along with many other languages), we place our regex inside of // blocks. The regex searching for a lowercase letter looks like this:


/[a-z]/


Replacing strings with regex


You can also use a regex to search and replace a file's contents as well. Say you wanted to replace any greeting with a message of "goodbye". While you could do something like this:


function youSayHelloISayGoodbye(str) {

  str = str.replace("Hello", "Goodbye");

  str = str.replace("Hi", "Goodbye");

  str = str.replace("Hey", "Goodbye");  str = str.replace("hello", "Goodbye");

  str = str.replace("hi", "Goodbye");

  str = str.replace("hey", "Goodbye");

  return str;

}


There's an easier alternative, using a regex:


function youSayHelloISayGoodbye(str) {

  str = str.replace(/[Hh]ello|[Hh]i|[Hh]ey/, "Goodbye");

  return str;

}


However, something you might notice is that if you run youSayHelloISayGoodbye with "Hello, Hi there": it won't match more than a single input:

If the regex /[Hh]ello|[Hh]i|[Hh]ey/ is used on the string "Hello, Hi there", it will only match "Hello" by default.

Here, we should expect to see both "Hello" and "Hi" matched, but we don't.

This is because we need to utilize a Regex "flag" to match more than once.


Flags


A regex flag is a modifier to an existing regex. These flags are always appended after the last forward slash in a regex definition.


Here's a shortlist of some of the flags available to you.


g - Global, match more than once

m - Force $ and ^ to match each newline individually

i - Make the regex case insensitive


This means that we could rewrite the following regex:


/[Hh]ello|[Hh]i|[Hh]ey/


To use the case insensitive flag instead:


/Hello|Hi|Hey/i


With this flag, this regex will now match:


Hello

HEY

Hi

HeLLo


Or any other case-modified variant.


Global regex flag with string replacing


As we mentioned before, if you do a regex replace without any flags it will only replace the first result:


let str = "Hello, hi there!";

str = str.replace(/[Hh]ello|[Hh]i|[Hh]ey/, "Goodbye");

console.log(str); // Will output "Goodbye, hi there"


However, if you pass the global flag, you'll match every instance of the greetings matched by the regex:


let str = "Hello, hi there!";

str = str.replace(/[Hh]ello|[Hh]i|[Hh]ey/g, "Goodbye");

console.log(str); // Will output "Goodbye, Goodbye there"


Groups


When searching with a regex, it can be helpful to search for more than one matched item at a time. This is where "groups" come into play. Groups allow you to search for more than a single item at a time.


Here, we can see matching against both Testing 123 and Tests 123 without duplicating the "123" matcher in the regex.


/(Testing|tests) 123/ig


Groups are defined by parentheses; there are two different types of groups--capture groups and non-capturing groups:


(...) - Group matching any three characters

(?:...) - Non-capturing group matching any three characters


The difference between these two typically comes up in the conversation when "replace" is part of the equation.

For example, using the regex above, we can use the following JavaScript to replace the text with "Testing 234" and "tests 234":


const regex = /(Testing|tests) 123/ig;


let str = `

Testing 123

Tests 123

`;


str = str.replace(regex, '$1 234');

console.log(str); // Testing 234\nTests 234"


We're using $1 to refer to the first capture group, (Testing|tests). We can also match more than a single group, like both (Testing|tests) and (123):


const regex = /(Testing|tests) (123)/ig;


let str = `

Testing 123

Tests 123

`;


str = str.replace(regex, '$1 #$2');

console.log(str); // Testing #123\nTests #123"


However, this is only true for capture groups. If we change:


/(Testing|tests) (123)/ig


To become:


/(?:Testing|tests) (123)/ig;


Then there is only one captured group – (123) – and instead, the same code from above will output something different:


const regex = /(?:Testing|tests) (123)/ig;


let str = `

Testing 123

Tests 123

`;


str = str.replace(regex, '$1');

console.log(str); // "123\n123"


Named capture groups


While capture groups are awesome, it can easily get confusing when there are more than a few capture groups. The difference between $3 and $5 isn't always obvious at a glance.


To help solve for this problem, regexes have a concept called "named capture groups"


(?<name>...) - Named capture group called "name" matching any three characters


You can use them in a regex like so to create a group called "num" that matches three numbers:


/Testing (?<num>\d{3})/


Then, you can use it in a replacement like so:


const regex = /Testing (?<num>\d{3})/

let str = "Testing 123";

str = str.replace(regex, "Hello $<num>")

console.log(str); // "Hello 123"


Named back reference


Sometimes it can be useful to reference a named capture group inside of a query itself. This is where "back references" can come into play.


\k<name> Reference named capture group "name" in a search query

Say you want to match:


Hello there James. James, how are you doing?


But not:


Hello there James. Frank, how are you doing?


While you could write a regex that repeats the word "James" like the following:


/.*James. James,.*/


A better alternative might look something like this:


/.*(?<name>James). \k<name>,.*/


Now, instead of having two names hardcoded, you only have one.


Lookahead and lookbehind groups


Lookahead and behind groups are extremely powerful and often misunderstood.

There are four different types of lookahead and behinds:

(?!) - negative lookahead

(?=) - positive lookahead

(?<=) - positive lookbehind

(?<!) - negative lookbehind


Lookahead works like it sounds like: It either looks to see that something is after the lookahead group or is not after the lookahead group, depending on if it's positive or negative.

As such, using the negative lookahead like so:


/B(?!A)/


Will allow you to match BC but not BA.


You can even combine these with ^ and $ tokens to try to match full strings. For example, the following regex will match any string that does not start with "Test"


/^(?!Test).*$/gm


Likewise, we can switch this to a positive lookahead to enforce that our string must start with "Test"


/^(?=Test).*$/gm


Putting it all together


Regexes are extremely powerful and can be used in a myriad of string manipulations. Knowing them can help you refactor codebases, script quick language changes, and more!


Let's go back to our initial phone number regex and try to understand it again:


^(?:\d{3}-){2}\d{4}$


Remember that this regex is looking to match phone numbers such as:


555-555-5555


Here this regex is:


  • Using ^ and $ to define the start and end of a regex line.
  • Using a non-capturing group to find three digits then a dash
  • Repeating this group twice, to match 555-555-
  • Finding the last 4 digits of the phone number


I hope you understood the Regular Expressions (Regex). If you have any doubts, please let us know in the comments.