Sitemap
Josh Cocciardi

Josh Cocciardi

Dad, Husband, Curious

RegEx Practice and Tips

5 min readFeb 25, 2019

In your coding travels you have probably come across RegEx and wondered what the heck all those forward and backslashes meant. After a little reading and practice, you can start implementing regular expressions in your code confidently and in very meaningful way. I actually found them to change the way I looked at some problems.

To start, here is a very basic expression, let’s walk through what is going on here and how quickly we can add to it to improve its usefulness.

const exampleReg = (/abc/)

Above, a simple variable is assigned the regex /abc/. This doesn’t do much on its own but when paired with a string and method…

“This is a string and it has in it the string abc”.match(exampleReg)=> 
["abc", index: 45, input: "This is a string and it has in it the string abc", groups: undefined]

Wow, what just happened? We used the exampleReg we created as an argument in the RegExp match method. It looked through the string it was executed on and returned and array with the matched string, the starting index of the match as well as the original input. Cool! But what if there are multiple matched and we want to see every time something occurs in a string?

Let’s use a new regex to try and achieve this.

const multpleReg = (/r/g)
“This is a string and it has in it the string abc”.match(multipleReg)
=>
"This is a string and it has in it the string abc".match(multipleReg)
(2) ["r", "r"]

What is different? We added what is called a flag after our search term.

/pattern/flags

We are looking for matches of the string ‘r’ which occurs twice in the string we are checking. To find multiple matches we use the ‘g’ flag. This flag continues to search after the first match is found. Flags are incredibly helpful and useful, here is another very helpful one, ‘i’, this makes your search case insensitive. Let’s check this out in practice, and oh by the way you can just put the regex right into the match method without separately declaring the variable for it.

'AaaaaaAAAaAH Real MONSTERS!'.match(/a/gi)=> (12) ["A", "a", "a", "a", "a", "a", "A", "A", "A", "a", "A", "a"]

Look at that, not only did we use the ‘g’ flag to find all the instances but we added the ‘i’ flag to get both the capital and lowercase matches. We now know how to use regex and .match to find basic matches in a string lookup, but what if you don’t know the exact letter or character you are looking for but instead need a pattern, say two letters in a row followed by a number?

'This is the string we are looking through for "aa3" two letters and a number'

Get Josh Cocciardi’s stories in your inbox

Join Medium for free to get updates from this writer.

Without a regex, how would you find this? Maybe use split and turn it into an array and then look through the array somehow? Hmmm, good thing we have some simple regex to help!

'This is the string we are looking through for "aa3" two letters and a number'.match(/\D\D\d/)=> ["aa3", index: 47, input: "This is the string we are looking through for "aa3" two letters and a number", groups: undefined]

RegExp provides some great search terms, by using /\/ the backslash escapes the direct letter search so we are not looking for a D, instead, capital D is a wildcard for any non-digit character while \d is any digit, MDN docs below.

Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9]. For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

Matches any digit (Arabic numeral). Equivalent to [0-9]. For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".

There are a ton of character cases, \S for example

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

This is powerful because we can very quickly turn a string into a more useful array of characters.

‘Some string with spaces, punctuation! and numbers 895.’.match(/\S/gi)=> (47) [“S”, “o”, “m”, “e”, “s”, “t”, “r”, “i”, “n”, “g”, “w”, “i”, “t”, “h”, “s”, “p”, “a”, “c”, “e”, “s”, “,”, “p”, “u”, “n”, “c”, “t”, “u”, “a”, “t”, “i”, “o”, “n”, “!”, “a”, “n”, “d”, “n”, “u”, “m”, “b”, “e”, “r”, “s”, “8”, “9”, “5”, “.”]//or we could try \w'Some string with spaces, punctuation! and numbers 895.'.match(/\w/gi)
(44) ["S", "o", "m", "e", "s", "t", "r", "i", "n", "g", "w", "i", "t", "h", "s", "p", "a", "c", "e", "s", "p", "u", "n", "c", "t", "u", "a", "t", "i", "o", "n", "a", "n", "d", "n", "u", "m", "b", "e", "r", "s", "8", "9", "5"]

\w can at once eliminate spaces and punctuation giving us a raw alphanumeric array.

There are many more flags and character searches you can use, feel free to peruse online but the MDN docs are great.

In addition to match there are also many other methods you can explore, quickly a particularly useful one .test, returns a boolean, this could be particularly useful in a filter for example. This uses a different arrangement, regex.test(string)

Here it is in practice:

(/hey/i).test('this string does not contain h3y')=> false

One interesting thing to note is that the pattern passed to a regex is taken literally, we cannot do the following:

const reg = (/hey/gi)
'some string'.match(reg)
=> null
// : (

Instead, we can take advantage of the OO nature of the RegExp class and really step up our regex game to the next level so we can say map through values and pass them into a regex without having to write each expression out manually.

const string = 'this is a sentence'
const string2 = 'ABBA'
string2.split('').filter(letter=>{
return (/letter/).test(string)
})

=> []

See, we cannot look for the letter as the pattern, we can however create a new regex object and test it that way!

const string3 = 'hi'.match(/./g)
//turns the string 'hi' into an array, the '.' is a complete wildcard
1 - string3.filter(letter=>{
2 - const
newReg = new RegExp(letter, 'gi')
3 - console.log(newReg)
4 - return (newReg).test(string)
5 - })
log:3 /h/gi
log:3 /i/gi
=>
(2) ["h", "i"]
the below is the console logging the regex being created on each loop. The letter is passed in as the pattern and the

What is happening here? Line 3 is being logged so we can see what the loop is creating, the regex pattern is the letter from the filter and the flags are added to the end. Now we can use an enumerable and create more dynamic pattern searches uses regex!

There is so much more you can do and learn but I found these few tools incredibly helpful in learning to use regex and add them to my toolbox. Explore online and read the MDN docs, they are helpful and you can get some creative ideas on how to apply regex. Also, keep in mind regex are common in most programming languages which means you are leaning a skill that translates well to whatever you learn next!

MDN RegExp
Great tool to practice RegEx!

--

--