{
"name": "Regular Expressions",
"order": 3,
"time": "5 hours",
"helpRoom": "Help",
"challenges": [
{
"id": "587d7db3367417b2b2512b8d",
"title": "Introduction to the Regular Expression Challenges",
"description": [
[
"https://camo.githubusercontent.com/85ac1a6783961ce77add6b2e8630dbf6521d33b2/687474703a2f2f696d67732e786b63642e636f6d2f636f6d6963732f726567756c61725f65787072657373696f6e732e706e67",
"XKCD web comic showing how regular expressions can save the day",
"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.",
""
]
],
"releasedOn": "Feb 17, 2017",
"challengeSeed": [],
"tests": [],
"type": "waypoint",
"challengeType": 7,
"isRequired": false,
"translations": {}
},
{
"id": "587d7db3367417b2b2512b8e",
"title": "Using the Test Method",
"description": [
"Regular expressions are used in programming languages to match parts of strings. You create patterns to help you do that matching.",
"If you want to find the word \"the\"
in the string \"The dog chased the cat\"
, you could use the following regular expression: /the/
. Notice that quote marks are not required within the regular expression.",
"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.",
"
let testStr = \"freeCodeCamp\";", "
let testRegex = /Code/;
testRegex.test(testStr);
// Returns true
myRegex
on the string myString
using the .test()
method."
],
"challengeSeed": [
"let myString = \"Hello, World!\";",
"let myRegex = /Hello/;",
"let result = myRegex; // Change this line"
],
"tests": [
"assert(code.match(/myRegex.test\\(\\s*myString\\s*\\)/), 'message: You should use .test()
to test the regex.');",
"assert(result === true, 'message: Your result should return true
.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db3367417b2b2512b8f",
"title": "Match Literal Strings",
"description": [
"In the last challenge, you searched for the word \"Hello\"
using the regular expression /Hello/
. That regex searched for a literal match of the string \"Hello\"
. Here's another example searching for a literal match of the string \"Kevin\"
:",
"let testStr = \"Hello, my name is Kevin.\";", "Any other forms of
let testRegex = /Kevin/;
testRegex.test(testStr);
// Returns true
\"Kevin\"
will not match. For example, the regex /Kevin/
will not match \"kevin\"
or \"KEVIN\"
.",
"let wrongRegex = /kevin/;", "A future challenge will show how to match those other forms as well.", "
wrongRegex.test(testStr);
// Returns false
waldoRegex
to find \"Waldo\"
in the string waldoIsHiding
with a literal match."
],
"challengeSeed": [
"let waldoIsHiding = \"Somewhere Waldo is hiding in this text.\";",
"let waldoRegex = /search/; // Change this line",
"let result = waldoRegex.test(waldoIsHiding);"
],
"tests": [
"assert(waldoRegex.test(waldoIsHiding), 'message: Your regex waldoRegex
should find \"Waldo\"
');",
"assert(!waldoRegex.test('Somewhere is hiding in this text.'), 'message: Your regex waldoRegex
should not search for anything else.');",
"assert(!/\\/.*\\/i/.test(code), 'message: You should perform a literal string match with your regex.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db4367417b2b2512b90",
"title": "Match a Literal String with Different Possibilities",
"description": [
"Using regexes like /coding/
, you can look for the pattern \"coding\"
in another string.",
"This is powerful to search single strings, but it's limited to only one pattern. 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/
.",
"You can also search for more than just two patterns. You can do this by adding more patterns with more OR
operators separating them, like /yes|no|maybe/
.",
"petRegex
to match the pets \"dog\"
, \"cat\"
, \"bird\"
, or \"fish\"
."
],
"challengeSeed": [
"let petString = \"James has a pet cat.\";",
"let petRegex = /change/; // Change this line",
"let result = petRegex.test(petString);"
],
"tests": [
"assert(petRegex.test('John has a pet dog.'), 'message: Your regex petRegex
should return true
for the string \"John has a pet dog.\"
');",
"assert(!petRegex.test('Emma has a pet rock.'), 'message: Your regex petRegex
should return false
for the string \"Emma has a pet rock.\"
');",
"assert(petRegex.test('Emma has a pet bird.'), 'message: Your regex petRegex
should return true
for the string \"Emma has a pet bird.\"
');",
"assert(petRegex.test('Liz has a pet cat.'), 'message: Your regex petRegex
should return true
for the string \"Liz has a pet cat.\"
');",
"assert(!petRegex.test('Kara has a pet dolphin.'), 'message: Your regex petRegex
should return false
for the string \"Kara has a pet dolphin.\"
');",
"assert(petRegex.test('Alice has a pet fish.'), 'message: Your regex petRegex
should return true
for the string \"Alice has a pet fish.\"
');",
"assert(!petRegex.test('Jimmy has a pet computer.'), 'message: Your regex petRegex
should return false
for the string \"Jimmy has a pet computer.\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db4367417b2b2512b91",
"title": "Ignore Case While Matching",
"description": [
"Up until now, you've looked at regexes to do literal matches of strings. But sometimes, you might want to also match case differences.",
"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\"
.",
"fccRegex
to match \"freeCodeCamp\"
, no matter its case. Your regex should not match any abbreviations or variations with spaces."
],
"challengeSeed": [
"let myString = \"freeCodeCamp\";",
"let fccRegex = /change/; // Change this line",
"let result = fccRegex.test(myString);"
],
"tests": [
"assert(fccRegex.test('freeCodeCamp'), 'message: Your regex should match freeCodeCamp
');",
"assert(fccRegex.test('FreeCodeCamp'), 'message: Your regex should match FreeCodeCamp
');",
"assert(fccRegex.test('FreecodeCamp'), 'message: Your regex should match FreecodeCamp
');",
"assert(fccRegex.test('FreeCodecamp'), 'message: Your regex should match FreeCodecamp
');",
"assert(!fccRegex.test('Free Code Camp'), 'message: Your regex should not match Free Code Camp
');",
"assert(fccRegex.test('FreeCOdeCamp'), 'message: Your regex should match FreeCOdeCamp
');",
"assert(!fccRegex.test('FCC'), 'message: Your regex should not match FCC
');",
"assert(fccRegex.test('FrEeCoDeCamp'), 'message: Your regex should match FrEeCoDeCamp
');",
"assert(fccRegex.test('FrEeCodECamp'), 'message: Your regex should match FrEeCodECamp
');",
"assert(fccRegex.test('FReeCodeCAmp'), 'message: Your regex should match FReeCodeCAmp
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db4367417b2b2512b92",
"title": "Extract Matches",
"description": [
"So far, you have only been checking if a pattern exists or not within a string. You can also 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. Here's an example:",
"\"Hello, World!\".match(/Hello/);", "
// Returns [\"Hello\"]
let ourStr = \"Regular expressions\";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
// Returns [\"expressions\"]
.match()
method to extract the word coding
."
],
"challengeSeed": [
"let extractStr = \"Extract the word 'coding' from this string.\";",
"let codingRegex = /change/; // Change this line",
"let result = extractStr; // Change this line"
],
"tests": [
"assert(result.join() === \"coding\", 'message: The result
should have the word coding
');",
"assert(codingRegex.source === \"coding\", 'message: Your regex codingRegex
should search for coding
');",
"assert(code.match(/\\.match\\(.*\\)/), 'message: You should use the .match()
method.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db4367417b2b2512b93",
"title": "Find More Than the First Match",
"description": [
"So far, you have only been able to extract or search a pattern once.",
"let testStr = \"Repeat, Repeat, Repeat\";", "To search or extract a pattern more than once, you can use the
let ourRegex = /Repeat/;
testStr.match(ourRegex);
// Returns [\"Repeat\"]
g
flag.",
"let repeatRegex = /Repeat/g;", "
testStr.match(repeatRegex);
// Returns [\"Repeat\", \"Repeat\", \"Repeat\"]
starRegex
, find and extract both \"Twinkle\"
words from the string twinkleStar
.",
"Note/search/gi
"
],
"challengeSeed": [
"let twinkleStar = \"Twinkle, twinkle, little star\";",
"let starRegex = /change/; // Change this line",
"let result = twinkleStar; // Change this line"
],
"tests": [
"assert(starRegex.flags.match(/g/).length == 1, 'message: Your regex starRegex
should use the global flag g
');",
"assert(starRegex.flags.match(/i/).length == 1, 'message: Your regex starRegex
should use the case insensitive flag i
');",
"assert(result.sort().join() == twinkleStar.match(/twinkle/gi).sort().join(), 'message: Your match should match both occurrences of the word \"Twinkle\"
');",
"assert(result.length == 2, 'message: Your match result
should have two elements in it.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db5367417b2b2512b94",
"title": "Match Anything with Wildcard Period",
"description": [
"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. For example, if you wanted to match \"hug\"
, \"huh\"
, \"hut\"
, and \"hum\"
, you can use the regex /hu./
to match all four words.",
"let humStr = \"I'll hum a song\";", "
let hugStr = \"Bear hug\";
let huRegex = /hu./;
humStr.match(huRegex); // Returns [\"hum\"]
hugStr.match(huRegex); // Returns [\"hug\"]
unRegex
so that it matches the strings \"run\"
, \"sun\"
, \"fun\"
, \"pun\"
, \"nun\"
, and \"bun\"
. Your regex should use the wildcard character."
],
"challengeSeed": [
"let exampleStr = \"Let's have fun with regular expressions!\";",
"let unRegex = /change/; // Change this line",
"let result = unRegex.test(exampleStr);"
],
"tests": [
"assert(code.match(/\\.test\\(.*\\)/), 'message: You should use the .test()
method.');",
"assert(/\\./.test(unRegex.source), 'message: You should use the wildcard character in your regex unRegex
');",
"assert(unRegex.test(\"Let us go on a run.\"), 'message: Your regex unRegex
should match \"run\"
in \"Let us go on a run.\"
');",
"assert(unRegex.test(\"The sun is out today.\"), 'message: Your regex unRegex
should match \"sun\"
in \"The sun is out today.\"
');",
"assert(unRegex.test(\"Coding is a lot of fun.\"), 'message: Your regex unRegex
should match \"fun\"
in \"Coding is a lot of fun.\"
');",
"assert(unRegex.test(\"Seven days without a pun makes one weak.\"), 'message: Your regex unRegex
should match \"pun\"
in \"Seven days without a pun makes one weak.\"
');",
"assert(unRegex.test(\"One takes a vow to be a nun.\"), 'message: Your regex unRegex
should match \"nun\"
in \"One takes a vow to be a nun.\"
');",
"assert(unRegex.test(\"She got fired from the hot dog stand for putting her hair in a bun.\"), 'message: Your regex unRegex
should match \"bun\"
in \"She got fired from the hot dog stand for putting her hair in a bun.\"
');",
"assert(!unRegex.test(\"There is a bug in my code.\"), 'message: Your regex unRegex
should not match \"There is a bug in my code.\"
');",
"assert(!unRegex.test(\"Can me if you can.\"), 'message: Your regex unRegex
should not match \"Catch me if you can.\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db5367417b2b2512b95",
"title": "Match Single Character with Multiple Possibilities",
"description": [
"You learned how to match literal patterns (/literal/
) and wildcard character (/./
). Those are the extremes of regular expressions, where one finds exact matches and the other matches everything. There are options that are a balance between the two extremes.",
"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.",
"For example, you want to match \"bag\"
, \"big\"
, and \"bug\"
but not \"bog\"
. You can create the regex /b[aiu]g/
to do this. The [aiu]
is the character class that will only match the characters \"a\"
, \"i\"
, or \"u\"
.",
"let bigStr = \"big\";", "
let bagStr = \"bag\";
let bugStr = \"bug\";
let bogStr = \"bog\";
let bgRegex = /b[aiu]g/;
bigStr.match(bgRegex); // Returns [\"big\"]
bagStr.match(bgRegex); // Returns [\"bag\"]
bugStr.match(bgRegex); // Returns [\"bug\"]
bogStr.match(bgRegex); // Returns null
a
, e
, i
, o
, u
) in your regex vowelRegex
to find all the vowels in the string quoteSample
.",
"NotevowelRegex
should use a character class.');",
"assert(vowelRegex.flags.match(/g/).length == 1, 'message: Your regex vowelRegex
should use the global flag.');",
"assert(vowelRegex.flags.match(/i/).length == 1, 'message: Your regex vowelRegex
should use the case insensitive flag.');",
"assert(!/[b-df-hj-np-tv-z]/gi.test(result.join()), 'message: Your regex should not match any consonants.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db5367417b2b2512b96",
"title": "Match Letters of the Alphabet",
"description": [
"You saw how you can use character sets
to specify a group of characters to match, but that's a lot of typing when you need to match a large range of characters (for example, every letter in the alphabet). Fortunately, there is a built-in feature that makes this short and simple.",
"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]
.",
"let catStr = \"cat\";", "
let batStr = \"bat\";
let matStr = \"mat\";
let bgRegex = /[a-e]at/;
catStr.match(bgRegex); // Returns [\"cat\"]
batStr.match(bgRegex); // Returns [\"bat\"]
matStr.match(bgRegex); // Returns null
quoteSample
.",
"NotealphabetRegex
should match 35 items.');",
"assert(alphabetRegex.flags.match(/g/).length == 1, 'message: Your regex alphabetRegex
should use the global flag.');",
"assert(alphabetRegex.flags.match(/i/).length == 1, 'message: Your regex alphabetRegex
should use the case insensitive flag.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db5367417b2b2512b97",
"title": "Match Numbers and Letters of the Alphabet",
"description": [
"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
.",
"Also, it is possible to combine a range of letters and numbers in a single character set.",
"let jennyStr = \"Jenny8675309\";", "
let myRegex = /[a-z0-9]/ig;
// matches all letters and numbers in jennyStr
jennyStr.match(myRegex);
h
and s
, and a range of numbers between 2
and 6
. Remember to include the appropriate flags in the regex."
],
"challengeSeed": [
"let quoteSample = \"Blueberry 3.141592653s are delicious.\";",
"let myRegex = /change/; // Change this line",
"let result = myRegex; // Change this line"
],
"tests": [
"assert(result.length == 17, 'message: Your regex myRegex
should match 17 items.');",
"assert(myRegex.flags.match(/g/).length == 1, 'message: Your regex myRegex
should use the global flag.');",
"assert(myRegex.flags.match(/i/).length == 1, 'message: Your regex myRegex
should use the case insensitive flag.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db6367417b2b2512b98",
"title": "Match Single Characters Not Specified",
"description": [
"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.",
"For example, /[^aeiou]/gi
matches all characters that are not a vowel. Note that characters like .
, !
, [
, @
, /
and white space are matched - the negated vowel character set only excludes the vowel characters.",
"myRegex
should match 9 items.');",
"assert(myRegex.flags.match(/g/).length == 1, 'message: Your regex myRegex
should use the global flag.');",
"assert(myRegex.flags.match(/i/).length == 1, 'message: Your regex myRegex
should use the case insensitive flag.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db6367417b2b2512b99",
"title": "Match Characters that Occur One or More Times",
"description": [
"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.",
"For example, /a+/g
would find one match in \"abc\"
and return [\"a\"]
. Because of the +
, it would also find a single match in \"aabc\"
and return [\"aa\"]
.",
"If it were instead checking the string \"abab\"
, it would find two matches and return [\"a\", \"a\"]
because the a
characters are not in a row - there is a b
between them. Finally, since there is no \"a\"
in the string \"bcd\"
, it wouldn't find a match.",
"s
occurs one or more times in \"Mississippi\"
. Write a regex that uses the +
sign."
],
"challengeSeed": [
"let difficultSpelling = \"Mississippi\";",
"let myRegex = /change/; // Change this line",
"let result = difficultSpelling.match(myRegex);"
],
"tests": [
"assert(/\\+/.test(myRegex.source), 'message: Your regex myRegex
should use the +
sign to match one or more s
characters.');",
"assert(result.length == 2, 'message: Your regex myRegex
should match 2 items.');",
"assert(result[0] == 'ss' && result[1] == 'ss', 'message: The result
variable should be an array with two matches of \"ss\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db6367417b2b2512b9a",
"title": "Match Characters that Occur Zero or More Times",
"description": [
"The last challenge used the plus +
sign to look for characters that occur one 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
: *
.",
"let sWord1 = \"seed\";", "
let sWord2 = \"saw\";
let kWord = \"kite\";
let sRegex = /s.*/; // Searches for words starting with s
sRegex.test(sWord1); // Returns true
sRegex.test(sWord2); // Returns true
sRegex.test(kWord); // Returns false
starWarsRegex
that uses the *
character to match all the movie titles that start with \"Star Wars\"
. Your regex does not need flags."
],
"challengeSeed": [
"let starWars = \"Star Wars\";",
"let starWarsRegex = /change/; // Change this line",
"let result = starWars.match(starWarsRegex);"
],
"tests": [
"assert(starWarsRegex.test(\"Star Wars: The Phantom Menace\"), 'message: Your regex should match \"Star Wars: The Phantom Menace\"
.');",
"assert(starWarsRegex.test(\"Star Wars: Attack of the Clones\"), 'message: Your regex should match \"Star Wars: Attack of the Clones\"
.');",
"assert(starWarsRegex.test(\"Star Wars: Revenge of the Sith\"), 'message: Your regex should match \"Star Wars: Revenge of the Sith\"
.');",
"assert(starWarsRegex.test(\"Star Wars: A New Hope\"), 'message: Your regex should match \"Star Wars: A New Hope\"
.');",
"assert(starWarsRegex.test(\"Star Wars: The Empire Strikes Back\"), 'message: Your regex should match \"Star Wars: The Empire Strikes Back\"
.');",
"assert(starWarsRegex.test(\"Star Wars: Return of the Jedi\"), 'message: Your regex should match \"Star Wars: Return of the Jedi\"
.');",
"assert(starWarsRegex.test(\"Star Wars: The Force Awakens\"), 'message: Your regex should match \"Star Wars: The Force Awakens\"
.');",
"assert(!starWarsRegex.test(\"The Clone Wars\"), 'message: Your regex should not match \"The Clone Wars\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db6367417b2b2512b9b",
"title": "Find Characters with Lazy Matching",
"description": [
"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.",
"You can apply the regex /t[a-z]*i/
to the string \"titanic\"
. This regex is basically a pattern that starts with t
, ends with i
, and has some letters in between.",
"Regular expressions are by default greedy
, so the match would return [\"titani\"]
. It finds the largest sub-string possible to fit the pattern.",
"However, you can use the ?
character to change it to lazy
matching. \"titanic\"
matched against the adjusted regex of /t[a-z]*?i/
returns [\"ti\"]
.",
"/<.*>/
to return the HTML tag <h1>
and not the text \"<h1>Winter is coming</h1>\"
. Remember the wildcard .
in a regular expression matches any character."
],
"challengeSeed": [
"let text = \"result
variable should be an array with <h1>
in it');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db7367417b2b2512b9c",
"title": "Find One or More Criminals in a Hunt",
"description": [
"Time to pause and test your new regex writing skills. A group of criminals escaped from jail and ran away, but you don't know how many. However, you do know that they stay close together when they are around other people. You are responsible for finding all of the criminals at once.",
"Here's an example to review how to do this:",
"The regex /z+/
matches the letter z
when it appears one or more times in a row. It would find matches in all of the following strings:",
"\"z\"", "But it does not find matches in the following strings since there are no letter
\"zzzzzz\"
\"ABCzzzz\"
\"zzzzABC\"
\"abczzzzzzzzzzzzzzzzzzzzzabc\"
z
characters:",
"\"\"", "
\"ABC\"
\"abcabc\"
greedy
regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter C
."
],
"challengeSeed": [
"// example crowd gathering",
"let crowd = 'P1P2P3P4P5P6CCCP7P8P9';",
"",
"let reCriminals = /./; // Change this line",
"",
"let matchedCriminals = crowd.match(reCriminals);",
"console.log(matchedCriminals);"
],
"tests": [
"assert('C'.match(reCriminals) && 'C'.match(reCriminals)[0] == 'C', 'message: Your regex should match one criminal (\"C
\") in \"C\"
');",
"assert('CC'.match(reCriminals) && 'CC'.match(reCriminals)[0] == 'CC', 'message: Your regex should match two criminals (\"CC
\") in \"CC\"
');",
"assert('P1P5P4CCCP2P6P3'.match(reCriminals) && 'P1P5P4CCCP2P6P3'.match(reCriminals)[0] == 'CCC', 'message: Your regex should match three criminals (\"CCC
\") in \"P1P5P4CCCP2P6P3\"
');",
"assert('P6P2P7P4P5CCCCCP3P1'.match(reCriminals) && 'P6P2P7P4P5CCCCCP3P1'.match(reCriminals)[0] == 'CCCCC', 'message: Your regex should match five criminals (\"CCCCC
\") in \"P6P2P7P4P5CCCCCP3P1\"
');",
"assert(!reCriminals.test(''), 'message: Your regex should not match any criminals in \"\"
');",
"assert(!reCriminals.test('P1P2P3'), 'message: Your regex should not match any criminals in \"P1P2P3\"
');",
"assert('P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals) && 'P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals)[0] == \"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\", 'message: Your regex should match fifty criminals (\"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
\") in \"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3\"
.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db7367417b2b2512b9d",
"title": "Match Beginning String Patterns",
"description": [
"Prior challenges showed that regular expressions can be used to look for a number of matches. They are also used to search for patterns in specific positions in strings.",
"In an earlier challenge, you used the caret
character (^
) inside a character set
to create a negated character set
in the form [^thingsThatWillNotBeMatched]
. Outside of a character set
, the caret
is used to search for patterns at the beginning of strings.",
"let firstString = \"Ricky is first and can be found.\";", "
let firstRegex = /^Ricky/;
firstRegex.test(firstString);
// Returns true
let notFirst = \"You can't find Ricky now.\";
firstRegex.test(notFirst);
// Returns false
caret
character in a regex to find \"Cal\"
only in the beginning of the string rickyAndCal
."
],
"challengeSeed": [
"let rickyAndCal = \"Cal and Ricky both like racing.\";",
"let calRegex = /change/; // Change this line",
"let result = calRegex.test(rickyAndCal);"
],
"tests": [
"assert(calRegex.source == \"^Cal\", 'message: Your regex should search for \"Cal\"
with a capital letter.');",
"assert(calRegex.flags == \"\", 'message: Your regex should not use any flags.');",
"assert(calRegex.test(\"Cal and Ricky both like racing.\"), 'message: Your regex should match \"Cal\"
at the beginning of the string.');",
"assert(!calRegex.test(\"Ricky and Cal both like racing.\"), 'message: Your regex should not match \"Cal\"
in the middle of a string.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db7367417b2b2512b9e",
"title": "Match Ending String Patterns",
"description": [
"In the last challenge, you learned to use the caret
character to search for patterns at the beginning of strings. There is also a way to search for patterns at the end of strings.",
"You can search the end of strings using the dollar sign
character $
at the end of the regex.",
"let theEnding = \"This is a never ending story\";", "
let storyRegex = /story$/;
storyRegex.test(theEnding);
// Returns true
let noEnding = \"Sometimes a story will have to end\";
storyRegex.test(noEnding);
// Returns false
$
) to match the string \"caboose\"
at the end of the string caboose
."
],
"challengeSeed": [
"let caboose = \"The last car on a train is the caboose\";",
"let lastRegex = /change/; // Change this line",
"let result = lastRegex.test(caboose);"
],
"tests": [
"assert(lastRegex.source == \"caboose$\", 'message: You should search for \"caboose\"
with the dollar sign $
anchor in your regex.');",
"assert(lastRegex.flags == \"\", 'message: Your regex should not use any flags.');",
"assert(lastRegex.test(\"The last car on a train is the caboose\"), 'message: You should match \"caboose\"
at the end of the string \"The last car on a train is the caboose\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db7367417b2b2512b9f",
"title": "Match All Letters and Numbers",
"description": [
"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 (_
).",
"let longHand = /[A-Za-z0-9_]+/;", "These shortcut character classes are also known as
let shortHand = /\\w+/;
let numbers = \"42\";
let varNames = \"important_var\";
longHand.test(numbers); // Returns true
shortHand.test(numbers); // Returns true
longHand.test(varNames); // Returns true
shortHand.test(varNames); // Returns true
shorthand character classes
.",
"\\w
to count the number of alphanumeric characters in various quotes and strings."
],
"challengeSeed": [
"let quoteSample = \"The five boxing wizards jump quickly.\";",
"let alphabetRegexV2 = /change/; // Change this line",
"let result = quoteSample.match(alphabetRegexV2).length;"
],
"tests": [
"assert(alphabetRegexV2.global, 'message: Your regex should use the global flag.');",
"assert(\"The five boxing wizards jump quickly.\".match(alphabetRegexV2).length === 31, 'message: Your regex should find 31 alphanumeric characters in \"The five boxing wizards jump quickly.\"
');",
"assert(\"Pack my box with five dozen liquor jugs.\".match(alphabetRegexV2).length === 32, 'message: Your regex should find 32 alphanumeric characters in \"Pack my box with five dozen liquor jugs.\"
');",
"assert(\"How vexingly quick daft zebras jump!\".match(alphabetRegexV2).length === 30, 'message: Your regex should find 30 alphanumeric characters in \"How vexingly quick daft zebras jump!\"
');",
"assert(\"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.\".match(alphabetRegexV2).length === 36, 'message: Your regex should find 36 alphanumeric characters in \"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db8367417b2b2512ba0",
"title": "Match Everything But Letters and Numbers",
"description": [
"You've learned that you can use a shortcut to match alphanumerics [A-Za-z0-9_]
using \\w
. A natural pattern you might want to search for is the opposite of alphanumerics.",
"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_]
.",
"let shortHand = /\\W/;", "
let numbers = \"42%\";
let sentence = \"Coding!\";
numbers.match(shortHand); // Returns [\"%\"]
sentence.match(shortHand); // Returns [\"!\"]
\\W
to count the number of non-alphanumeric characters in various quotes and strings."
],
"challengeSeed": [
"let quoteSample = \"The five boxing wizards jump quickly.\";",
"let nonAlphabetRegex = /change/; // Change this line",
"let result = quoteSample.match(nonAlphabetRegex).length;"
],
"tests": [
"assert(nonAlphabetRegex.global, 'message: Your regex should use the global flag.');",
"assert(\"The five boxing wizards jump quickly.\".match(nonAlphabetRegex).length == 6, 'message: Your regex should find 6 non-alphanumeric characters in \"The five boxing wizards jump quickly.\"
.');",
"assert(\"Pack my box with five dozen liquor jugs.\".match(nonAlphabetRegex).length == 8, 'message: Your regex should find 8 non-alphanumeric characters in \"Pack my box with five dozen liquor jugs.\"
');",
"assert(\"How vexingly quick daft zebras jump!\".match(nonAlphabetRegex).length == 6, 'message: Your regex should find 6 non-alphanumeric characters in \"How vexingly quick daft zebras jump!\"
');",
"assert(\"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.\".match(nonAlphabetRegex).length == 12, 'message: Your regex should find 12 non-alphanumeric characters in \"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "5d712346c441eddfaeb5bdef",
"title": "Match All Numbers",
"description": [
"You've learned shortcuts for common string patterns like alphanumerics. Another common pattern is looking for just digits or numbers.",
"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.",
"\\d
to count how many digits are in movie titles. Written out numbers (\"six\" instead of 6) do not count."
],
"challengeSeed": [
"let numString = \"Your sandwich will be $5.00\";",
"let numRegex = /change/; // Change this line",
"let result = numString.match(numRegex).length;"
],
"tests": [
"assert(/\\\\d/.test(numRegex.source), 'message: Your regex should use the shortcut character to match digit characters');",
"assert(numRegex.global, 'message: Your regex should use the global flag.');",
"assert(\"9\".match(numRegex).length == 1, 'message: Your regex should find 1 digit in \"9\"
.');",
"assert(\"Catch 22\".match(numRegex).length == 2, 'message: Your regex should find 2 digits in \"Catch 22\"
.');",
"assert(\"101 Dalmatians\".match(numRegex).length == 3, 'message: Your regex should find 3 digits in \"101 Dalmatians\"
.');",
"assert(\"One, Two, Three\".match(numRegex) == null, 'message: Your regex should find no digits in \"One, Two, Three\"
.');",
"assert(\"21 Jump Street\".match(numRegex).length == 2, 'message: Your regex should find 2 digits in \"21 Jump Street\"
.');",
"assert(\"2001: A Space Odyssey\".match(numRegex).length == 4, 'message: Your regex should find 4 digits in \"2001: A Space Odyssey\"
.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db8367417b2b2512ba1",
"title": "Match All Non-Numbers",
"description": [
"The last challenge showed how to search for digits using the shortcut \\d
with a lowercase d
. 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 [^0-9]
, which looks for a single character that is not a number between zero and nine.",
"\\D
to count how many non-digits are in movie titles."
],
"challengeSeed": [
"let numString = \"Your sandwich will be $5.00\";",
"let noNumRegex = /change/; // Change this line",
"let result = numString.match(noNumRegex).length;"
],
"tests": [
"assert(/\\\\D/.test(noNumRegex.source), 'message: Your regex should use the shortcut character to match non-digit characters');",
"assert(noNumRegex.global, 'message: Your regex should use the global flag.');",
"assert(\"9\".match(noNumRegex) == null, 'message: Your regex should find no non-digits in \"9\"
.');",
"assert(\"Catch 22\".match(noNumRegex).length == 6, 'message: Your regex should find 6 non-digits in \"Catch 22\"
.');",
"assert(\"101 Dalmatians\".match(noNumRegex).length == 11, 'message: Your regex should find 11 non-digits in \"101 Dalmatians\"
.');",
"assert(\"One, Two, Three\".match(noNumRegex).length == 15, 'message: Your regex should find 15 non-digits in \"One, Two, Three\"
.');",
"assert(\"21 Jump Street\".match(noNumRegex).length == 12, 'message: Your regex should find 12 non-digits in \"21 Jump Street\"
.');",
"assert(\"2001: A Space Odyssey\".match(noNumRegex).length == 17, 'message: Your regex should find 17 non-digits in \"2001: A Space Odyssey\"
.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db8367417b2b2512ba2",
"title": "Restrict Possible Usernames",
"description": [
"Usernames are used everywhere on the internet. They are what give users a unique identity on their favorite sites.",
"You need to check all the usernames in a database. Here are some simple rules that users have to follow when creating their username.",
"1) The only numbers in the username have to be at the end. There can be zero or more of them at the end.",
"2) Username letters can be lowercase and uppercase.",
"3) Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.",
"userCheck
to fit the constraints listed above."
],
"challengeSeed": [
"let username = \"JackOfAllTrades\";",
"let userCheck = /change/; // Change this line",
"let result = userCheck.test(username);"
],
"tests": [
"assert(userCheck.test(\"JACK\"), 'message: Your regex should match JACK
');",
"assert(!userCheck.test(\"J\"), 'message: Your regex should not match J
');",
"assert(userCheck.test(\"Oceans11\"), 'message: Your regex should match Oceans11
');",
"assert(userCheck.test(\"RegexGuru\"), 'message: Your regex should match RegexGuru
');",
"assert(!userCheck.test(\"007\"), 'message: Your regex should not match 007
');",
"assert(!userCheck.test(\"9\"), 'message: Your regex should not match 9
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db8367417b2b2512ba3",
"title": "Match Whitespace",
"description": [
"The challenges so far have covered matching letters of the alphabet and numbers. You can also match the whitespace or spaces between letters.",
"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]
.",
"let whiteSpace = \"Whitespace. Whitespace everywhere!\"", "
let spaceRegex = /\\s/g;
whiteSpace.match(spaceRegex);
// Returns [\" \", \" \"]
countWhiteSpace
to look for multiple whitespace characters in a string."
],
"challengeSeed": [
"let sample = \"Whitespace is important in separating words\";",
"let countWhiteSpace = /change/; // Change this line",
"let result = sample.match(countWhiteSpace);"
],
"tests": [
"assert(countWhiteSpace.global, 'message: Your regex should use the global flag.');",
"assert(\"Men are from Mars and women are from Venus.\".match(countWhiteSpace).length == 8, 'message: Your regex should find eight spaces in \"Men are from Mars and women are from Venus.\"
');",
"assert(\"Space: the final frontier.\".match(countWhiteSpace).length == 3, 'message: Your regex should find three spaces in \"Space: the final frontier.\"
');",
"assert(\"MindYourPersonalSpace\".match(countWhiteSpace) == null, 'message: Your regex should find no spaces in \"MindYourPersonalSpace\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db9367417b2b2512ba4",
"title": "Match Non-Whitespace Characters",
"description": [
"You learned about searching for whitespace using \\s
, with a lowercase s
. You can also search for everything except whitespace.",
"Search for non-whitespace using \\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]
.",
"let whiteSpace = \"Whitespace. Whitespace everywhere!\"", "
let nonSpaceRegex = /\\S/g;
whiteSpace.match(nonSpaceRegex).length; // Returns 32
countNonWhiteSpace
to look for multiple non-whitespace characters in a string."
],
"challengeSeed": [
"let sample = \"Whitespace is important in separating words\";",
"let countNonWhiteSpace = /change/; // Change this line",
"let result = sample.match(countNonWhiteSpace);"
],
"tests": [
"assert(countNonWhiteSpace.global, 'message: Your regex should use the global flag.');",
"assert(\"Men are from Mars and women are from Venus.\".match(countNonWhiteSpace).length == 35, 'message: Your regex should find 35 non-spaces in \"Men are from Mars and women are from Venus.\"
');",
"assert(\"Space: the final frontier.\".match(countNonWhiteSpace).length == 23, 'message: Your regex should find 23 non-spaces in \"Space: the final frontier.\"
');",
"assert(\"MindYourPersonalSpace\".match(countNonWhiteSpace).length == 21, 'message: Your regex should find 21 non-spaces in \"MindYourPersonalSpace\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db9367417b2b2512ba5",
"title": "Specify Upper and Lower Number of Matches",
"description": [
"Recall that you use the plus sign +
to look for one or more characters and the asterisk *
to look for zero or more characters. These are convenient but sometimes you want to match a certain range of patterns.",
"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/
.",
"let A4 = \"aaaah\";", "
let A2 = \"aah\";
let multipleA = /a{3,5}h/;
multipleA.test(A4); // Returns true
multipleA.test(A2); // Returns false
ohRegex
to match only 3
to 6
letter h
's in the word \"Oh no\"
."
],
"challengeSeed": [
"let ohStr = \"Ohhh no\";",
"let ohRegex = /change/; // Change this line",
"let result = ohRegex.test(ohStr);"
],
"tests": [
"assert(ohRegex.source.match(/{.*?}/).length > 0, 'message: Your regex should use curly brackets.');",
"assert(!ohRegex.test(\"Ohh no\"), 'message: Your regex should not match \"Ohh no\"
');",
"assert(ohRegex.test(\"Ohhh no\"), 'message: Your regex should match \"Ohhh no\"
');",
"assert(ohRegex.test(\"Ohhhh no\"), 'message: Your regex should match \"Ohhhh no\"
');",
"assert(ohRegex.test(\"Ohhhhh no\"), 'message: Your regex should match \"Ohhhhh no\"
');",
"assert(ohRegex.test(\"Ohhhhhh no\"), 'message: Your regex should match \"Ohhhhhh no\"
');",
"assert(!ohRegex.test(\"Ohhhhhhh no\"), 'message: Your regex should not match \"Ohhhhhhh no\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db9367417b2b2512ba6",
"title": "Specify Only the Lower Number of Matches",
"description": [
"You can specify the lower and upper number of patterns with quantity specifiers
using curly brackets. Sometimes you only want to specify the lower number of patterns with no upper limit.",
"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/
.",
"let A4 = \"haaaah\";", "
let A2 = \"haah\";
let A100 = \"h\" + \"a\".repeat(100) + \"h\";
let multipleA = /ha{3,}h/;
multipleA.test(A4); // Returns true
multipleA.test(A2); // Returns false
multipleA.test(A100); // Returns true
haRegex
to match the word \"Hazzah\"
only when it has four or more letter z
's."
],
"challengeSeed": [
"let haStr = \"Hazzzzah\";",
"let haRegex = /change/; // Change this line",
"let result = haRegex.test(haStr);"
],
"tests": [
"assert(haRegex.source.match(/{.*?}/).length > 0, 'message: Your regex should use curly brackets.');",
"assert(!haRegex.test(\"Hazzah\"), 'message: Your regex should not match \"Hazzah\"
');",
"assert(!haRegex.test(\"Hazzzah\"), 'message: Your regex should not match \"Hazzzah\"
');",
"assert(haRegex.test(\"Hazzzzah\"), 'message: Your regex should match \"Hazzzzah\"
');",
"assert(haRegex.test(\"Hazzzzzah\"), 'message: Your regex should match \"Hazzzzzah\"
');",
"assert(haRegex.test(\"Hazzzzzzah\"), 'message: Your regex should match \"Hazzzzzzah\"
');",
"assert(haRegex.test(\"Ha\" + \"z\".repeat(30) + \"ah\"), 'message: Your regex should match \"Hazzah\"
with 30 z
\\'s in it.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7db9367417b2b2512ba7",
"title": "Specify Exact Number of Matches",
"description": [
"You can specify the lower and upper number of patterns with quantity specifiers
using curly brackets. Sometimes you only want a specific number of matches.",
"To specify a certain number of patterns, just have that one number between the curly brackets.",
"For example, to match only the word \"hah\"
with the letter a
3
times, your regex would be /ha{3}h/
.",
"let A4 = \"haaaah\";", "
let A3 = \"haaah\";
let A100 = \"h\" + \"a\".repeat(100) + \"h\";
let multipleHA = /a{3}h/;
multipleHA.test(A4); // Returns false
multipleHA.test(A3); // Returns true
multipleHA.test(A100); // Returns false
timRegex
to match the word \"Timber\"
only when it has four letter m
's."
],
"challengeSeed": [
"let timStr = \"Timmmmber\";",
"let timRegex = /change/; // Change this line",
"let result = timRegex.test(timStr);"
],
"tests": [
"assert(timRegex.source.match(/{.*?}/).length > 0, 'message: Your regex should use curly brackets.');",
"assert(!timRegex.test(\"Timber\"), 'message: Your regex should not match \"Timber\"
');",
"assert(!timRegex.test(\"Timmber\"), 'message: Your regex should not match \"Timmber\"
');",
"assert(!timRegex.test(\"Timmmber\"), 'message: Your regex should not match \"Timmmber\"
');",
"assert(timRegex.test(\"Timmmmber\"), 'message: Your regex should match \"Timmmmber\"
');",
"assert(!timRegex.test(\"Ti\" + \"m\".repeat(30) + \"ber\"), 'message: Your regex should not match \"Timber\"
with 30 m
\\'s in it.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7dba367417b2b2512ba8",
"title": "Check for All or None",
"description": [
"Sometimes the patterns you want to search for may have parts of it that may or may not exist. However, it may be important to check for them nonetheless.",
"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.",
"For example, there are slight differences in American and British English and you can use the question mark to match both spellings.",
"let american = \"color\";", "
let british = \"colour\";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true
rainbowRegex.test(british); // Returns true
favRegex
to match both the American English (favorite) and the British English (favourite) version of the word."
],
"challengeSeed": [
"let favWord = \"favorite\";",
"let favRegex = /change/; // Change this line",
"let result = favRegex.test(favWord);"
],
"tests": [
"assert(favRegex.source.match(/\\?/).length > 0, 'message: Your regex should use the optional symbol, ?
.');",
"assert(favRegex.test(\"favorite\"), 'message: Your regex should match \"favorite\"
');",
"assert(favRegex.test(\"favourite\"), 'message: Your regex should match \"favourite\"
');",
"assert(!favRegex.test(\"fav\"), 'message: Your regex should not match \"fav\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7dba367417b2b2512ba9",
"title": "Positive and Negative Lookahead",
"description": [
"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 but some examples will help.",
"let quit = \"qu\";", "A more practical use of
let noquit = \"qt\";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex); // Returns [\"q\"]
noquit.match(qRegex); // Returns [\"q\"]
lookaheads
is to check two or more patterns in one string. Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number:",
"let password = \"abc123\";", "
let checkPass = /(?=\\w{3,6})(?=\\D*\\d)/;
checkPass.test(password); // Returns true
lookaheads
in the pwRegex
to match passwords that are greater than 5 characters long and have two consecutive digits."
],
"challengeSeed": [
"let sampleWord = \"astronaut\";",
"let pwRegex = /change/; // Change this line",
"let result = pwRegex.test(sampleWord);"
],
"tests": [
"assert(pwRegex.source.match(/\\(\\?=.*?\\)\\(\\?=.*?\\)/) !== null, 'message: Your regex should use two positive lookaheads
.');",
"assert(!pwRegex.test(\"astronaut\"), 'message: Your regex should not match \"astronaut\"
');",
"assert(!pwRegex.test(\"airplanes\"), 'message: Your regex should not match \"airplanes\"
');",
"assert(pwRegex.test(\"bana12\"), 'message: Your regex should match \"bana12\"
');",
"assert(pwRegex.test(\"abc123\"), 'message: Your regex should match \"abc123\"
');",
"assert(!pwRegex.test(\"123\"), 'message: Your regex should not match \"123\"
');",
"assert(!pwRegex.test(\"1234\"), 'message: Your regex should not match \"1234\"
');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7dbb367417b2b2512baa",
"title": "Reuse Patterns Using Capture Groups",
"description": [
"Some patterns you search for will occur multiple times in a string. It is wasteful to manually repeat that regex. There is a better way to specify when you have multiple repeat substrings in your string.",
"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 example below matches any word that occurs twice separated by a space:",
"let repeatStr = \"regex regex\";", "Using the
let repeatRegex = /(\\w+)\\s\\1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns [\"regex regex\", \"regex\"]
.match()
method on a string will return an array with the string it matches, along with its capture group.",
"capture groups
in reRegex
to match numbers that appear three times in a string each separated by a space."
],
"challengeSeed": [
"let repeatNum = \"42 42 42\";",
"let reRegex = /change/; // Change this line",
"let result = reRegex.test(repeatNum);"
],
"tests": [
"assert(reRegex.source.match(/\\\\d/), 'message: Your regex should use the shorthand character class for digits.');",
"assert(reRegex.source.match(/\\\\\\d/g).length === 2, 'message: Your regex should reuse the capture group twice.');",
"assert(reRegex.source.match(/\\\\s/g).length === 2, 'message: Your regex should have two spaces separating the three numbers.');",
"assert(reRegex.test(\"42 42 42\"), 'message: Your regex should match \"42 42 42\"
.');",
"assert(reRegex.test(\"100 100 100\"), 'message: Your regex should match \"100 100 100\"
.');",
"assert.equal((\"42 42 42 42\").match(reRegex.source)[0], (\"42 42 42\"), 'message: Your regex should not match \"42 42 42 42\"
.');",
"assert.equal((\"42 42\").match(reRegex.source), null, 'message: Your regex should not match \"42 42\"
.');",
"assert(!reRegex.test(\"101 102 103\"), 'message: Your regex should not match \"101 102 103\"
.');",
"assert(!reRegex.test(\"1 2 3\"), 'message: Your regex should not match \"1 2 3\"
.');",
"assert(reRegex.test(\"10 10 10\"), 'message: Your regex should match \"10 10 10\"
.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7dbb367417b2b2512bab",
"title": "Use Capture Groups to Search and Replace",
"description": [
"Searching is useful. However, you can make searching even more powerful when it also changes (or replaces) the text you match.",
"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.",
"let wrongText = \"The sky is silver.\";", "You can also access capture groups in the replacement string with dollar signs (
let silverRegex = /silver/;
wrongText.replace(silverRegex, \"blue\");
// Returns \"The sky is blue.\"
$
).",
"\"Code Camp\".replace(/(\\w+)\\s(\\w+)/, '$2 $1');", "
// Returns \"Camp Code\"
\"good\"
. Then update the replaceText
variable to replace \"good\"
with \"okey-dokey\"
."
],
"challengeSeed": [
"let huhText = \"This sandwich is good.\";",
"let fixRegex = /change/; // Change this line",
"let replaceText = \"\"; // Change this line",
"let result = huhText.replace(fixRegex, replaceText);"
],
"tests": [
"assert(code.match(/\\.replace\\(.*\\)/), 'message: You should use .replace()
to search and replace.');",
"assert(result == \"This sandwich is okey-dokey.\" && replaceText === \"okey-dokey\", 'message: Your regex should change \"This sandwich is good.\"
to \"This sandwich is okey-dokey.\"
');",
"assert(code.match(/result\\s*=\\s*huhText\\.replace\\(.*?\\)/), 'message: You should not change the last line.');"
],
"solutions": [],
"hints": [],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
},
{
"id": "587d7dbb367417b2b2512bac",
"title": "Remove Whitespace from Start and End",
"description": [
"Sometimes whitespace characters around strings are not wanted but are there. Typical processing of strings is to remove the whitespace at the start and end of it.",
".trim()
method would work here, but you'll need to complete this challenge using regular expressions."
],
"challengeSeed": [
"let hello = \" Hello, World! \";",
"let wsRegex = /change/; // Change this line",
"let result = hello; // Change this line"
],
"tests": [
"assert(result == \"Hello, World!\", 'message: result
should equal to \"Hello, World!\"
');",
"assert(!code.match(/\\.trim\\(.*?\\)/), 'message: You should not use the .trim()
method.');",
"assert(!code.match(/result\\s*=\\s*\".*?\"/), 'message: The result
variable should not be set equal to a string.');"
],
"solutions": [],
"hints": [
"You can use .replace() to remove the matched items by replacing them with an empty string."
],
"type": "waypoint",
"releasedOn": "Feb 17, 2017",
"challengeType": 1,
"translations": {}
}
]
}