Regex For Mortals
Regex For Mortals - 11/01/2020
This is an ongoing project to make Regex more understandable for myself and others.
One of the scary things about regex is how intimidating it looks. It's appearance alone could even turn away experienced programmers if they didn't know what it could accomplish. Often appearing as nothing more than a scrambled mess of symbols, it's not easy to see how you could use it quickly. Here's an example:
/[A-Za-z0-9+-?.]/*
How is that a piece of code that can filter a string based on characters you may ask? We need to take it apart piece by piece in order to answer that. Firstly let's start with the forward slash.
Regex is either contained within forward slashes, or a Regex object is created and contained in quotations, such as:
newRegex = new RegExp('pattern')
So this pattern simply indicates that something is contained within regex:
/regex/
Regex can either filter out entire words or just characters. If regex is going to be applied as a single filter, no additional syntax is needed besides the slashes. If multiple characters need to be filtered out, brackets indicate that there is a range of characters to filter, and a dash indicates all characters in between the range. The below code indicates all letters from r to x, or r, s, t, u, v, w, x, y, z:
/[r-x]/
If you're thinking "that's great, but how do I apply regex?". Well very little else is needed to apply regex. Depending on the language, particular functions might work well with regex, but in general you can just treat it like any other string. For instance in JavaScript, if you're replacing some characters in one string with another, you could just do something like:
let s = thisIsAString
let replacement = "Replaced"
s.replace("AString", replacement)
If you wanted to use regex, you could just take out the value of what to replace, "AString", with regex. This will simply replace everything that is selected by the regex with the replacement string:
let s = thisIsAString
let replacement = "Replaced"
s.replace(/A/, replacement)
Might not be the best example, but that's one way to use the replace method to implement regex.