DEV Community

SCDan0624
SCDan0624

Posted on

Javascript Regex Part 3 More Character Matching

Negated character set

Negated character sets are a set of characters you do not want to match. To create a negated character set you place ^ after the opening bracket. Here is an example:

let mySample = "Hello" let myRegex = /[^aeiou]/gi let result = mySample.match(myRegex) console.log(result) // [ 'H', 'l', 'l' ] 
Enter fullscreen mode Exit fullscreen mode

Match characters that occur 0 or more times

To search for characters that occur 0 or more times you use an * after the word:

let happy = "yessssss" let myRegex = /yes/ let myRegex2 = /yes*/ happy.match(myRegex) //'yes' happy.match(myRegex2) // 'yessssss' 
Enter fullscreen mode Exit fullscreen mode

Match characters that occur 1 or more times

You can also match characters that occur 1 or more times using the + symbol after the word:

let happy = "aabc" let myRegex = /a/ let myRegex2 = /a+/ happy.match(myRegex) //'a' happy.match(myRegex2) //'aa' 
Enter fullscreen mode Exit fullscreen mode

Lazy matching

A lazy match finds the smallest part of the string that satisfies the regex pattern.

To use lazy matching put a ? after the characters you are searching for:

let happy = "basketball" let myRegex = /b[a-k]l/ // not lazy matching or 'greedy matching' let myRegex2 = /b[a-k]l?/ //lazy matching happy.match(myRegex) //'bal' happy.match(myRegex2) //'ba' 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)