* vs + in Regex when searching for words in a sentence

ishan vimukthi
Jun 14, 2021

REGEx ??? ok some Programmers love 😍 it and others don't 🤬 but no matter you love or hate it regex is a powerful and flexible tool 😇.

Most common use case of the regex is to split a sentence into words. we can do it via using * or + (code example in javascript)).

console.log(“ishan vimukthi vihanga kandage don”.match(/\w*/g));

console.log(“ishan vimukthi vihanga kandage don”.match(/\w+/g));

output

(using *) [“ishan”, “”, “vimukthi”, “”, “vihanga”, “”, “kandage”, “”, “don”, “”]

(using +) [“ishan”, “vimukthi”, “vihanga”, “kandage”, “don”]

\wWord. Matches any word character (alphanumeric & underscore).

*Quantifier. Match 0 or more of the preceding token.

+Quantifier. Match 1 or more of the preceding token.

(this happen because empty space is considered in * but not in + so + is more suitable to select words from a sentence ) 👋👋👋👋

--

--