Regex Flashcards
see if the word ‘bobcat’ has an ‘o’ in it
> /o/.test(‘bobcat’)
= true
see if the word ‘bobcat’ has an ‘l’ in it
> /l/.test(‘bobcat’)
= false
What’s the difference between .test and .exec?
the exec() method will return the specified match if present or null if not present in the given string whereas the test() method returns a Boolean result
How would you capture the char after ‘the’ in ‘The big dog jumps’?
let string ‘The big dog jumps’;
let regex= /[tT]he(.)/g;
let result = regex.exec(string)
//will capture the char after ‘The’
How do we create a capture group?
using ().
How do we name a capture group? and then use that capture group
using ?<name> at the beginning of our group definition</name>
let namedRegex = /[Tt]he(?<charAfterThe>.)/g
let namedResult = namedRegex.exec(string)
let charAfter = namedResult.groups.charAfterThe</charAfterThe>
how would you match all 4 or 5 letter words
/\w{4,5}/
match any word after the word ‘the’
/(?<=[tT]he )\w+/g
match any word before the word ‘the’
/\w*(?= [tT]he)/g
+
matches one or more in a row
ie /e+/g will find all ‘e’ or multiple ‘e’ substrings
?
- optional
- ie
/e+a?/g
will find all ‘e’ or ‘ee’ or ‘ea’ substrings - also changes * when chained ?. makes the behavior non-greedy. repetition will first try to match asfew*reps as possible
*
- match 0 or more
- ie
/re*/g
will find all ‘r’ or ‘re’ or ‘ree’
.
matches anything except a newline
\
escape char
if you need to seach say for a period you can say /./g
\w
matches any word char, so any letter
\W
will match anything thats NOT a word char
\s
will match any white space
\S
matches anything that is not white space
\d
matches any number digit
\b
enforces a word break
function hasThanks(str) {
return /\b(thanks|thank you)\b/i.test(str);
}
hasThanks(“Thanks! You helped me a lot.”); // true
hasThanks(“Just want to say thank you for all your work.”); // true
hasThanks(“Thanksgiving is around the corner.”); // false
{}
- specifies the number of chars
-
/\w{4}/
will get any 4 letter words -
/\w{4,6}/
will get any words between 4 and 6 letters
[]
- matches any chars inside the brackets
-
/[ft]at/g
will find all 3 letter words starting with f or t and ending in at. - words with ranges [a-z] or [0-9A-Z]
()
- allows you to create groupings
- anything after the grouping will affect the whole grouping ie
/(t|e|r){2,3}/
will capture any 2 to 3 character long string of t, r, and e - these groups are also called capture groups and allow you to ‘capture’ each group to modify it later
-
(t|T)
allows you to match lower case t or upper caseT -
(t|T)he
matches any occurrence of ‘the’ or ‘The’ -
(re){2,3}
will find any instances of ‘rere’ or ‘rerere’
- match only to the beginning of the line.
- ^T will find capital T at the beginning of the line
- WHEN USE INSIDE A CHAR GROUP CAN ALSO BE USED TO REPRESENT NOT
- ie [^s] means match any char that isnt S
$
matches to the end of the statement