Different * and + flag in regex?

This task and my code not work as i expect : not same result * and + flag in regex
The lessons explain the differrence between * and + that either one or more times find pattern the other zero or more times.

But i dont get anything with : *

let exampleString = "iiiiiiiiiCCCCiiiii";

let exampleRegex1 = /C+/;
let exampleRegex2 = /C*/;

let result1 = exampleString.match(exampleRegex1);
let result2 = exampleString.match(exampleRegex2);

console.log(`result1: ${result1}`);
console.log(`result2: ${result2}`);

and the result:

result1: CCCC

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

Challenge: Find One or More Criminals in a Hunt

Link to the challenge:

so the things like β€œ+” or β€œ*” are called tokens. The things like β€œg”, β€œi” that follows a regex are known as flags.

without a β€œg” flag, your regex returns the first match found and does not continue any further in the input string.

since your exampleRegex2 matches β€œthe character β€˜c’ 0 or more times”, it goes to the very beginning of the word, says, β€œhey this non-character before the first character β€˜i’ looks like 0 β€˜C’”, and just returns you an empty string.

In other words it matches the empty string before the first char, since technically an empty string is 0 β€˜C’.

See into how regex works and play around with them using https://regex101.com/

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.