Regex solutions freecodecamp

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.

Regex, Part 1/6

Using the Test Method

enlightened 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.

angel The solution → let result = myRegex.text(myString);

 

Match Literal Strings

enlightenedA literal match of the a string can be like: “Kevin”

angel The solution → Waldo

 

Match a Literal String with Different Possibilities

enlightenedYou 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/.

angel The solution → /dog|cat|bird|fish/

 

Ignore Case While Matching

enlightenedCase (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”.

angel The solution → /freeCodeCamp/i

 

Extract Matches

enlightened 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.

angel The solution → /coding/

 

Find More Than the First Match

enlightenedTo 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

angel The solution → /Twinkle/gi

 

You can also watch the video where I talk and code the next few regex challenges.

Regex, Part 2/6

Match Anything with Wildcard Period

enlightenedSometimes 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.

angel The solution → /.un/

 

Match Single Character with Multiple Possibilities

enlightenedYou 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.

angel The solution → /[eaiou]/gi

 

Match Letters of the Alphabet

enlightenedInside 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].

angel The solution → /[a-z]/gi

 

Match Numbers and Letters of the Alphabet

enlightenedUsing 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.

angel The solution → /[h-s2–6]/gi

 

Match Single Characters Not Specified

enlightenedSo 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.

angel The solution → /[0-9aeiou]/gi

 

Match Characters that Occur One or More Times

enlightened 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.

angel The solution → /s+/g

 

Match Characters that Occur Zero or More Times

enlightenedThere’s also an option that matches characters that occur zero or more times. The character to do this is the asterisk or star: *.

angel The solution → /Aa*/

 

You can also watch the video where I talk and code the next few regex challenges.

Regex, part 3/6

Find Characters with Lazy Matching

enlightenedIn 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.

angel The solution → /<[h1].*?>/

 

Find One or More Criminals in a Hunt

angel The solution → /C+/

 

Match Beginning String Patterns

enlightenedOutside of a character set, the caret is used to search for patterns at the beginning of strings.

angel The solution → /^Cal/

 

Match Ending String Patterns

enlightened You can search the end of strings using the dollar sign character $ at the end of the regex.

angel The solution → /Caboose$/

 

You can also watch the video where I talk and code the next few regex challenges.

Regex, Part 4/6

Match All Letters and Numbers

enlightenedUsing 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 (_).

angel The solution → /\w/g

 

Match Everything But Letters and Numbers

enlightenedYou 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_].

angel The solution → /\W/g

 

Match All Numbers

enlightenedThe 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.

angel The solution → /\d/g

 

Match All Non-Numbers

enlightenedYou 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.

angel The solution → /\D/g

 

Restrict Possible Usernames

angel The solution → /[a-zA-Z][a-zA-Z]+/

 

You can also watch the video where I talk and code the next few regex challenges.

Regex, part 5/6

Match Whitespace

enlightenedYou 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].

angel The solution → /\s/g

 

Match Non-Whitespace Characters

enlightenedFor 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].

angel The solution → /\S/g

 

Specify Upper and Lower Number of Matches

enlightenedYou 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/.

angel The solution → /Oh{3,6}\s/g

 

Specify Only the Lower Number of Matches

enlightenedTo 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/.

angel The solution → /z{4,}/

 

Specify Exact Number of Matches

enlightenedTo specify a certain number of patterns, just have that one number between the curly brackets.

angel The solution → /Tim{4}ber/

 

Check for All or None

enlightenedYou 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.

angelThe solution → /favou?rite/

 

You can also watch the last video where I talk and code the next few regex challenges.

Regex, part 6/6

Positive and Negative Lookahead

enlightenedLookaheads 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

angelThe solution → /(?=\w{5,})(?=\D*\d)/

 

Reuse Patterns Using Capture Groups

enlightenedYou 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.

angel The solution → /^(\d+)\s\1\s\1$/

 

Use Capture Groups to Search and Replace

enlightenedYou 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.

angel The solution → /good/ 

and “okey-dokey”

 

Remove Whitespace from Start and End

angelThe 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