Skip to content

Instantly share code, notes, and snippets.

@NickFoden
Last active March 22, 2021 23:54
Show Gist options
  • Save NickFoden/eb4b53ea88865142692d7fddaf0564c8 to your computer and use it in GitHub Desktop.
Save NickFoden/eb4b53ea88865142692d7fddaf0564c8 to your computer and use it in GitHub Desktop.
Random Stuff

Introduction to the Regular Expression Challenges

This is note of regular expression from freecodecamp

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

Regular Expressions: Using the Test Method

  • 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

Regular Expressions: Match a Literal String with Different Possibilities

  • You can search for multiple patterns using the alternation or OR operator: |.
  • Example:
let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString);

Regular Expressions: Ignore Case While Matching

  • 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".
  • Example: Write a regex fccRegex to match "freeCodeCamp", no matter its case.
let myString = "freeCodeCamp";
let fccRegex = /freeCodeCamp/i;
let result = fccRegex.test(myString);

Regular Expressions: Extract Matches

  • To use the .match() method, apply the method on a string and pass in the regex inside the parentheses.
  • Example:
"Hello, World!".match(/Hello/);
// Returns ["Hello"]
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
// Returns ["expressions"]

Regular Expressions: Find More Than the First Match

  • To search or extract a pattern more than once, you can use the g flag.
  • Example:
let testStr = "Repeat, Repeat, Repeat";
let repeatRegex = /Repeat/g;
testStr.match(repeatRegex);
// Returns ["Repeat", "Repeat", "Repeat"]

Regular Expressions: Match Anything with Wildcard Period

  • 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.
  • Example:
let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr); // Returns true
huRegex.test(hugStr); // Returns true

Regular Expressions: 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.
  • Example:
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

Regular Expressions: Match Letters of the Alphabet

  • Inside a character set, you can define a range of characters to match using a hyphen character: -.
  • Example:
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

Regular Expressions: Match Numbers and Letters of the Alphabet

  • it is possible to combine a range of letters and numbers in a single character set.
  • Example:
let jennyStr = "Jenny8675309";
let myRegex = /[a-z0-9]/ig;
// matches all letters and numbers in jennyStr
jennyStr.match(myRegex);

Regular Expressions: Match Single Characters Not Specified

  • 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.
  • Example: Create a single regex that matches all characters that are not a number or a vowel.
let quoteSample = "3 blind mice.";
let myRegex = /[^aeiou^0-9]/gi; // Change this line
let result = quoteSample.match(myRegex); // Change this line

Regular Expressions: 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.
  • You can use the + character to check if that is the case. Remember, the character or pattern has to be present consecutively.
  • 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"].
  • Example: You want to find matches when the letter s occurs one or more times in "Mississippi". Write a regex that uses the + sign.
let difficultSpelling = "Mississippi";
let myRegex = /s+/g; // this is the solution
let result = difficultSpelling.match(myRegex);

Regular Expressions: Match Characters that Occur Zero or More Times

  • The character to do this is the asterisk or star: *.
let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // Returns ["goooooooo"]
gPhrase.match(goRegex); // Returns ["g"]
oPhrase.match(goRegex); // Returns null

Regular Expressions: 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.

  • you can use the ? character to change it to lazy matching. "titanic" matched against the adjusted regex of /t[a-z]*?i/ returns ["ti"].

  • Note: Parsing HTML with regular expressions should be avoided, but pattern matching an HTML string with regular expressions is completely fine.

  • Example: Fix the regex /<.*>/ 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.

let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*?>/; // it's the answer!
let result = text.match(myRegex);

Regular Expressions: Match Beginning String Patterns

  • 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.
  • Example:
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

Regular Expressions: Match Ending String Patterns

  • You can search the end of strings using the dollar sign character $ at the end of the regex.
  • Example:
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

Regular Expressions: Match All Letters and Numbers

  • 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 (_).
  • Example:
let longHand = /[A-Za-z0-9_]+/;
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

Regular Expressions: 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_].
let shortHand = /\W/;
let numbers = "42%";
let sentence = "Coding!";
numbers.match(shortHand); // Returns ["%"]
sentence.match(shortHand); // Returns ["!"]

Regular Expressions: Match All 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.

Regular Expressions: Match All Non-Numbers

  • \D is equal to [^0-9], which look for a single character that is not a number between zero and nine
  • Example : Use the shorthand character class for non-digits \D to count how many non-digits are in movie titles.
let movieName = "2001: A Space Odyssey";
let noNumRegex = /\D/g;
let result = movieName.match(noNumRegex).length;

Regaular Expressions: Restrict Possible Usernames

  • some simple rules that users have to follow when creating their username
  1. Usernames can only use alpha-numeric characters
  2. The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
  3. Username letters can be lowercase and uppercase.
  4. Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
  • Example: Change the regex userCheck to fit the constraints listed above.
Solution 1
  1. ^ - start of input
  2. [a-z] - first character is a letter
  3. [0-9][0-9]+ - ends with two or more numbers
  4. | - or
  5. [a-z]+ - has one or more letters next
  6. \d* - and ends with zero or more numbers
  7. $ - end of input
  8. i - ignore case of input
let username = "JackOfAllTrades";
let userCheck = /^[a-z]([0-9][0-9]+|[a-z]+\d*)$/i;
let result = userCheck.test(username);
Solution 2
  1. ^ - start of input
  2. [a-z] - first character is a letter
  3. [0-9]{2,0} - ends with two or more numbers
  4. | - or
  5. [a-z]+ - has one or more letters next
  6. \d* - and ends with zero or more numbers
  7. $ - end of input
  8. i - ignore case of input
let username = "JackOfAllTrades";
const userCheck = /^[a-z]([0-9]{2,}|[a-z]+\d*)$/i;
let result = userCheck.test(username);

Regular Expressions: Match Whitespace

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

Example: Change the regex countWhiteSpace to look for multiple whitespace characters in a string.

let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s/g; 
let result = sample.match(countWhiteSpace);

Regular Expressions: Match Non-Whitespace Characters

  • Search for non-whitespace using \S, which is an uppercase s.

  • Example: Change the regex countNonWhiteSpace to look for multiple non-whitespace characters in a string.

let sample = "Whitespace is important in separating words";
let countNonWhiteSpace = /\S/g; 
let result = sample.match(countNonWhiteSpace);

Regular Expressions: 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.

  • Example: Change the regex ohRegex to match the entire phrase "Oh no" only when it has 3 to 6 letter h's.

let ohStr = "Ohhh no";
let ohRegex = /Oh{3,6}\sno/; 
let result = ohRegex.test(ohStr);

Regular Expressions: Specify Only the Lower Number of Matches

  • 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

Regular Expressions: Specify Exact Number of Matches

  • Sometimes you only want a specific number of matches.
  • Example: Change the regex timRegex to match the word "Timber" only when it has four letter m's.
let timStr = "Timmmmber";
let timRegex = /Tim{4}ber/;
let result = timRegex.test(timStr);

Regular Expressions: Check for All or None

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

Regular Expressions: 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.
  • 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.
  • Example 1:
let quit = "qu";
let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex); // Returns ["q"]
noquit.match(qRegex); // Returns ["q"]
  • Example 2: A more practical use of 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
  • Example 3: Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits.
let sampleWord = "astronaut";
var pwRegex =  /^\D(?=\w{5})(?=\w*\d{2})/;
let result = pwRegex.test(sampleWord);

Regular Expressions: Check For Mixed Grouping of Characters

  • Sometimes we want to check for groups of characters using a Regular Expression and to achieve that we use parentheses ().
  • Example:
    • Fix the regex so that it checks for the names of Franklin Roosevelt or leanor Roosevelt in a case sensitive manner and it should make concessions for middle names.
    • Then fix the code so that the regex that you have created is checked against myString and either true or false is returned depending on whether the regex matches.
let myString = "Eleanor Roosevelt";
let myRegex = /(Franklin|Eleanor).*Roosevelt/;
let result = myRegex.test(myString);

Regular Expressions: Reuse Patterns Using Capture Groups

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

Note: \1 stand for the first capture group ( ), \2 stand for the second capture group ( )

  • Example: Use capture groups in reRegex to match numbers that are repeated only three times in a string, each separated by a space.
let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/; 

// this is equal to /^(\d+)\s(\d+)\s(\d+)$/

let result = reRegex.test(repeatNum);

Regular Expressions: 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.

  • Example 1:

let wrongText = "The sky is silver.";
let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");
// Returns "The sky is blue."
  • Example 2: You can also access capture groups in the replacement string with dollar signs ($).m
"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');
// Returns "Camp Code"
  • Example 3: Your regex should change "one two three" to "three two one"
let str = "one two three";
let fixRegex = /(\w+)\s(\w+)\s(\w+)/; 
let replaceText = "$3 $2 $1"; 
let result = str.replace(fixRegex, replaceText);

Regular Expressions: Remove Whitespace from Start and End

  • Typical processing of strings is to remove the whitespace at the start and end of it.
  • Example :
    • Write a regex and use the appropriate string methods to remove whitespace at the beginning and end of strings.
    • Note: The String.prototype.trim() method would work here, but you'll need to complete this challenge using regular expressions.
let hello = "   Hello, World!  ";
let wsRegex = /^\s+|\s+$/g; 
let result = hello.replace(wsRegex, ""); 
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment