Regex Flashcards
What are the two ways to create regular expressions in JS?
Constructor: new RegExp(pattern[,flags]) e.g. let regex = new RegExp('abc','i');
Literal: /pattern/flags
e.g.
let regex = /abc/i;
Both expressions would match against a sequence of a then b then c in a string ignoring case e.g. Abcre, baBC etc.
I want to know if the word ‘lite’ appears in a sentence and get a simple true/false response.
What regular expression method would I use?
test
e.g.
let regex = /lite/
let sentence = ‘ no such lite light’
let isPresent = regex.test(sentence)
isPresent = true;
How would I search the string ‘the quick brown Fox’ for the letter ‘f’ no matter the case?
let regex = /f/i
regex.test(‘the quick brown Fox’)
How would I get an array of all the capital letters in the sentence “The capital of Scotland is Edinburgh”.
let regex = /[A-Z]/g //all capital letters, do not stop at first match. let result = "The capital of Scotland is Edinburgh.".match(regex); result = ['T', 'S', 'E' ];
How would the result change if I removed the global flag from this regular expression operation?
let result = “17 Mall Road”.match(/\d/g);
The result of “17 Mall Road”.match(/\d/g) is [“1”, “7”].
Without the global flag it would only return the first match i.e. the number 1.
Write a regular expression that matches words containing bar and car.
/b|car/
or
/[bc]ar/
What is a character set?
A character set is a way to match different characters in a single position. It matches any string that contains any of the characters within the brackets
e.g. /[bcd]/
would match anyword containing b, c or d..
It is similar to or i.e. (b | c | d)
What are the different ways that the carat symbol ^ can be used in regular expressions?
- At the beginning of a character set, within the brackets e.g. /[^kl]e/
Here it means NOT k, NOT L. It matches anything NOT included in the character set.
- At the beginning of the regex proceeding the regex. e.g. /^p/
Here it means the string must start with p and will match ‘poll’ but not ‘nap’, for example.
Write a regular expression to find lowercase letters.
/[a-z]/g
This is a range. Instead of writing [abcdefg…etc.], you can use this shorthand.
Write a regular expression to find any digit character.
/[0-9]/
OR
/\d/
\d is a meta character, a shorthand for writing [0-9]
What will the following regex match?
/\s/
Any whitespace characters e.g. spaces, tabs
What is a word character?
Write a regular expression to find any word characters?
A word character is any alphanumeric character (letters and digits) in addition to the underscore i.e.
/[a-zA-Z0-9_]/
or
/\w/
\w is a meta character
Write a regular expression to match any non digit character.
/[^0-9]/
OR
/\D/
Write a regular expression to match any non word character.
/[^a-zA-Z0-9]/
OR
/\W/
What meta character matches any character except for a new line?
full stop i.e. .