Free Code Camp: Regular Expressions Challenges
Walkthrough and solutions. This article will walk you through freecodecamp.org regular expressions challenges.
-Regular expressions are special strings that represent a search pattern. Also known as “regex” or “regexp”, they help programmers match, search, and replace text. Regular expressions can appear cryptic because a few characters have special meaning. The goal is to combine the symbols and text into a pattern that matches what you want, but only what you want. This section will cover the characters, a few shortcuts, and the common uses for writing regular expressions. — by FreeCodeCamp
You can find the regular expressions challenges here
Let’s start!
You can also watch the video where I talk and code the first few regex challenges.
💡 Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching.
JavaScript has multiple ways to use regexes. One way to test a regex is using the .test() method. The .test() method takes the regex, applies it to a string (which is placed inside the parentheses), and returns true or false if your pattern finds something or not.
✅ The solution → let result = myRegex.text(myString);
💡 A literal match of the string can be like: “Kevin”
✅ The solution → Waldo
Match a Literal String with Different Possibilities
💡 You can search for multiple patterns using the alternation or OR operator:|.
This operator matches patterns either before or after it. For example, if you wanted to match “yes” or “no”, the regex you want is /yes|no/.
✅ The solution → /dog|cat|bird|fish/
💡 Case (or sometimes letter case) is the difference between uppercase letters and lowercase letters. Examples of uppercase are “A”, “B”, and “C”. Examples of lowercase are “a”, “b”, and “c”.
You can match both cases using what is called a flag. There are other flags but here you’ll focus on the flag that ignores case — the i flag. You can use it by appending it to the regex. An example of using this flag is /ignorecase/i. This regex can match the strings “ignorecase”, “igNoreCase”, and “IgnoreCase”.
✅ The solution → /freeCodeCamp/i
💡 You can extract the actual matches you found with the .match() method.
To use the .match() method, apply the method on a string and pass in the regex inside the parentheses.
✅ The solution → /coding/
Find More Than the First Match
💡 To search or extract a pattern more than once, you can use the g flag.
Note: You can have multiple flags on your regex like /search/gi
✅ The solution → /Twinkle/gi
You can also watch the video where I talk and code the next few regex challenges.
Match Anything with Wildcard Period
💡 Sometimes you won’t (or don’t need to) know the exact characters in your patterns. Thinking of all words that match, say, a misspelling would take a long time. Luckily, you can save time using the wildcard character: .
The wildcard character . will match any one character. The wildcard is also called dot and period. You can use the wildcard character just like any other character in the regex.
✅ The solution → /.un/
Match Single Character with Multiple Possibilities
💡 You can search for a literal pattern with some flexibility with character classes. Character classes allow you to define a group of characters you wish to match by placing them inside square ([ and ]) brackets.
✅ The solution → /[eaiou]/gi
💡 Inside a character set, you can define a range of characters to match using a hyphen character: -. For example, to match lowercase letters a through e you would use [a-e].
✅ The solution → /[a-z]/gi
Match Numbers and Letters of the Alphabet
💡 Using the hyphen (-) to match a range of characters is not limited to letters. It also works to match a range of numbers. For example, /[0–5]/ matches any number between 0 and 5, including the 0 and 5.
✅ The solution → /[h-s2–6]/gi
Match Single Characters Not Specified
💡 So far, you have created a set of characters that you want to match, but you could also create a set of characters that you do not want to match. These types of character sets are called negated character sets. To create a negated character set, you place a caret character (^) after the opening bracket and before the characters you do not want to match.
✅ The solution → /[0-9aeiou]/gi
Match Characters that Occur One or More Times
💡 Sometimes, you need to match a character (or group of characters) that appears one or more times in a row. This means it occurs at least once, and may be repeated. You can use the + character to check if that is the case. Remember, the character or pattern has to be present consecutively. That is, the character has to repeat one after the other.
✅ The solution → /s+/g
Match Characters that Occur Zero or More Times
💡 There’s also an option that matches characters that occur zero or more times. The character to do this is the asterisk or star: *.
✅ The solution → /Aa*/
You can also watch the video where I talk and code the next few regex challenges.
Find Characters with Lazy Matching
💡 In regular expressions, a greedy match finds the longest possible part of a string that fits the regex pattern and returns it as a match. The alternative is called a lazy match, which finds the smallest possible part of the string that satisfies the regex pattern.
✅ The solution → /<[h1].*?>/
Find One or More Criminals in a Hunt
✅ The solution → /C+/
Match Beginning String Patterns
💡 Outside of a character set, the caret is used to search for patterns at the beginning of strings.
✅ The solution → /^Cal/
💡 You can search the end of strings using the dollar sign character $ at the end of the regex.
✅ The solution → /Caboose$/
You can also watch the video where I talk and code the next few regex challenges.
💡 Using character classes, you were able to search for all letters of the alphabet with [a-z]. This kind of character class is common enough that there is a shortcut for it, although it includes a few extra characters as well.
The closest character class in JavaScript to match the alphabet is \w. This shortcut is equal to [A-Za-z0–9_]. This character class matches upper and lowercase letters plus numbers. Note, this character class also includes the underscore character (_).
✅ The solution → /\w/g
Match Everything But Letters and Numbers
💡 You can search for the opposite of the \w with \W. Note, the opposite pattern uses a capital letter. This shortcut is the same as [^A-Za-z0–9_].
✅ The solution → /\W/g
💡 The shortcut to look for digit characters is \d, with a lowercase d. This is equal to the character class [0–9], which looks for a single character of any number between zero and nine.
✅ The solution → /\d/g
💡 You can also search for non-digits using a similar shortcut that uses an uppercase D instead. The shortcut to look for non-digit characters is \D. This is equal to the character class [⁰-9], which looks for a single character that is not a number between zero and nine.
✅ The solution → /\D/g
✅ The solution → /[a-zA-Z][a-zA-Z]+/
You can also watch the video where I talk and code the next few regex challenges.
💡 You can search for whitespace using \s, which is a lowercase s. This pattern not only matches whitespace, but also carriage return, tab, form feed, and new line characters. You can think of it as similar to the character class [ \r\t\f\n\v].
✅ The solution → /\s/g
Match Non-Whitespace Characters
💡 For non-whitespace use \S, which is an uppercase s. This pattern will not match whitespace, carriage return, tab, form feed, and new line characters. You can think of it being similar to the character class [^ \r\t\f\n\v].
✅ The solution → /\S/g
Specify Upper and Lower Number of Matches
💡 You can specify the lower and upper number of patterns with quantity specifiers. Quantity specifiers are used with curly brackets ({ and }). You put two numbers between the curly brackets — for the lower and upper number of patterns. For example, to match only the letter a appearing between 3 and 5 times in the string “ah”, your regex would be /a{3,5}h/.
✅ The solution → /Oh{3,6}\s/g
Specify Only the Lower Number of Matches
💡 To only specify the lower number of patterns, keep the first number followed by a comma. For example, to match only the string “hah” with the letter a appearing at least 3 times, your regex would be /ha{3,}h/.
✅ The solution → /z{4,}/
Specify Exact Number of Matches
💡 To specify a certain number of patterns, just have that one number between the curly brackets.
✅ The solution → /Tim{4}ber/
💡 You can specify the possible existence of an element with a question mark, ?. This checks for zero or one of the preceding element. You can think of this symbol as saying the previous element is optional.
✅ The solution → /favou?rite/
You can also watch the last video where I talk and code the next few regex challenges.
Positive and Negative Lookahead
💡 Lookaheads are patterns that tell JavaScript to look-ahead in your string to check for patterns further along. This can be useful when you want to search for multiple patterns over the same string. There are two kinds of lookaheads: positive lookahead and negative lookahead.
A positive lookahead will look to make sure the element in the search pattern is there, but won’t actually match it. A positive lookahead is used as (?=…) where the … is the required part that is not matched.
On the other hand, a negative lookahead will look to make sure the element in the search pattern is not there. A negative lookahead is used as (?!…) where the … is the pattern that you do not want to be there. The rest of the pattern is returned if the negative lookahead part is not present.
Lookaheads are a bit confusing
✅ The solution → /(?=\w{5,})(?=\D*\d)/
Reuse Patterns Using Capture Groups
💡 You can search for repeat substrings using capture groups. Parentheses, ( and ), are used to find repeat substrings. You put the regex of the pattern that will repeat in between the parentheses.
To specify where that repeat string will appear, you use a backslash (\) and then a number. This number starts at 1 and increases with each additional capture group you use. An example would be \1 to match the first group.
✅ The solution → /^(\d+)\s\1\s\1$/
Use Capture Groups to Search and Replace
💡 You can search and replace text in a string using .replace() on a string. The inputs for .replace() is first the regex pattern you want to search for. The second parameter is the string to replace the match or a function to do something.
✅ The solution → /good/
and “okey-dokey”
Remove Whitespace from Start and End
✅ The solution → /^\s*(\w, \s*\w+!)\s*$/
and result = hello.replace(wsRegex, $1)
Are you still here?! Well, if you are congratulations! You just finished the regex challenges by freecodecamp!
Disclaimer: Regex definitions are by freecodecamp.org
Would you like to get me a coffee?!☕️
You can do that here → paypal.me/eleftheriabatsou
But If you can’t, that’s ok too 😍.