Like I said yesterday, I wanted to spend some time focusing on walking through some regex basics so that I can hopefully get them stuck in my head once and for all.
Today is going to be the first of a multi part journey (probably 3 days) of me trying to get something to stick.
What’s the point?
Regular expressions are a super efficient way of searching through strings. It allows for pattern matching to pull out pieces of text you’re interested in.
A regex consists of a query between two forward slashes, with optional flags following the trailing slash:
Flags can be used to modify the query, like telling it to find more than one match, look across multiple lines, etc.
The query itself can be written in a bunch of different ways which will be covered further down below. In the most basic example, if you were to put
dog inside of the query, you would be matching exactly on
.test() method. This will return back a
true/false whether or not the string has been matched.
let sampleString = "This is a string"; let regex = /is a/; regex.test(sampleString); // true
The above will return back true, as
is a is found within the
If you want to match off of more than just one word/set of characters, you can use an or
| to tell the regex to look for multiple matches:
let petString = "I have a dog"; let petReg = /dog|cat|bird|fish/; petReg.test(petString); // true
By default, all queries are case sensitive. That’s to say that a query of
dog will not match a string with
Dog in it.
This can be fixed by using a case insensitive query flag,
let petString = "I have a Dog named Navi"; (/dog/g).test(petString); // false (/dog/gi).test(petString); // true
If you actually want to extract the value that matches the query, you can use the
.match() is used on the string rather than the regex itself:
let extractStr = "Extract the word 'coding' from this string."; let result = extractStr.match(/coding/g); // result = ["coding"]
Matching More Than First Match
By default only the first match will be found before the string is no longer scanned.
To force the full string to be looked at for multiple matches, the
g flag must be included.