using regex Flashcards

1
Q

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.

A

let testStr = “freeCodeCamp”;
let testRegex = /Code/;
testRegex.test(testStr);

inser the string you are looking for inside of the forward slashes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

you can search for multiple words by using the OR operator within the forward slashes

A

for example /dog|cat|bird/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a regex fccRegex to match freeCodeCamp, no matter its case. Your regex should not match any abbreviations or variations with spaces.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

To use the .match() method, apply the method on a string and pass in the regex inside the parentheses.

A

“Hello, World!”.match(/Hello/);
let ourStr = “Regular expressions”;
let ourRegex = /expressions/;
ourStr.match(ourRegex);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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.

A
let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr);
huRegex.test(hugStr);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Using the hyphen (-) to match a range of characters is not limited to letters. It also works to match a range of numbers.

A

let jennyStr = “Jenny8675309”;
let myRegex = /[a-z0-9]/ig;
jennyStr.match(myRegex);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A

let whiteSpace = “Whitespace. Whitespace everywhere!”
let spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

You can search for non white space with \S

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly