Can anyone tell me why would I ever want to use * when I have + regex?

why would anyone want to match 0 characters or more vs 1 character or more? Can’t picture it.

Some boolean outcome difference?

If if I have:

ac
abc
abbc
abbbc

Do I want to match all of them (ab*c)? Or all but the first (ab+c)?

if it’s (ab*c), I’ll include that match ac as well.
If I use (ab+c), I’ll skip ac and match the rest.
Correct?

1 Like

regex (ab*c) match would return as follow.
ac
abc
abbc
abbbc

Regex (ab+c) match would return as follow:
null
abc
abbc
abbbc

sometimes I don’t care:
I can deal with some spaces in the string, lets say.
But I also can be fine without any spaces in the string.

The above means - zero or more spaces, right.

Sometimes I need string which has at least one space. Or more. It is different thing.

That’s why * and + both are a thing

It depends on how you are consuming those.

const testString = "She likes ac like abc apple jack abbc ribbit abbbc yeppers."

console.log(testString.match(/ab*c/g))
// ['ac', 'abc', 'abbc', 'abbbc']

console.log(testString.match(/ab+c/g))
// ['abc', 'abbc', 'abbbc']
1 Like

Look, regex is confusing. And complicated. But it is also insanely powerful and is one of the most developed and tested systems in coding. Give it a chance.

I find that using online regex playgrounds like regex 101 and others to be very helpful. I can never remember all the rules, so I just look them up when I need them and test them out there.

1 Like

Lots and lots of situation where you want zero or more, but the most common is probably optional whitespace, like if I want to match “hello” in a string but the string could be

"hello"

or

"      hello"

or

"                          hello                 "

Edit: that’s a silly example. For a more realistic example, say I want to match a CSS comment, just the text. Comment can be any of these (many other variations but I’ll just pick a few):

/* I am a "comment" */

 /* I am a comment */

/********************
 * I am a comment?
 */

/*I am a comment*/

/**
I am a comment.
*/

So pattern is

optional whitespace
literal "/*"
optional whitespace or "*"
{Actual comment text, anything up until "*/"}
optional whitespace
literal "*/"

Which is (ish):

\s*\/\*[\s\*]*(\w.+?(?=[\s\*]*\*\/))[\s\*]*\*\/gm

This is stupidly complex to look at and it isn’t even very good (there are a load of situations where it just won’t match), but here’s the link to it on regexr, if you click on the “Explain” tab at the bottom it will go though it bit by bit

2 Likes