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