Regular Expressions Note 1: or logic pipe, wildcard, i flag, g flag
One aspect of programming which I often time needed is text or string processing. I often need to reach out to regex (Regular Expression), but honestly most of the time I have no idea what I was typing 😂.
Starting here I'll note some of the things I learned on Regular Expression, so that (hopefully) I will not be as clueless as the usual.
We can match string with
or logic using pipe
const stringToMatch = "I love to eat carrot" const foodRegex = /carrot|pizza|apple/ const result = foodRegex.test(stringToMatch)
Ignore case sensitivity
When matching using regex the default is we also match the case. To match regex ignoring the case we add
i flag to the regex.
const stringToMatch = "Do you like to eat VEGETABLE?" const vegRegexCaseSensitive = /vegetable/ const vegRegexCaseInsensitive = /vegetable/i const caseSensitiveResult = vegRegexCaseSensitive.test(stringToMatch) const caseInsensitiveResult = vegRegexCaseInsensitive.test(stringToMatch)
Wildcard for matching any character
To match any character we can use
const stringToMatch = "The bug in the bag is pretty big" const regexWithWildcard = /b.g/ const matchResults = stringToMatch.match(regexWithWildcard)
Global flag for matching all occurances
The previous examples only return/match the first occurance of string matched with the regex. To find/match all occurances we can use the
g (global) flag on the regex.
const stringToMatch = "The bug in the bag is pretty big" const regexWithWildcard = /b.g/g const matchResults = stringToMatch.match(regexWithWildcard)