1

I started learning regex recently. I know that * modifier means match 0 or more times while + modifier means match 1 or more times.

However when you use these modifiers with square brackets, how will the code get parsed? It seems to me that using square brackets would equalize the + and *.

For example: What is the difference between [\w\s,:]+ and [\w\s,:]*?

2

The difference is exactly that you wrote. The characters in the set may occur once to multiple times with + and may also not occur at all with * .

| improve this answer | |
  • so [...|]+ will be equal to [...]*? – One Face Feb 11 '15 at 0:35
  • 1
    Ummm ... no. [] defines a character class. Adding a pipe symbol to that won't do what you think it does. It's NOT grouping. Also three dots inside [] don't make sense. They're literals in there. – tink Feb 11 '15 at 0:38
  • 1
    @C Rags: Assuming your dots stand for any set of characters. No, they are not the same. The left one will match any non-empty sequence of those characters plus the pipe character, while the right one will only match sequences of those characters in any amount including zero. – Janis Feb 11 '15 at 0:52
  • 4
    @CRags, no, but ([...]+|) will be equal to [...]* – Mark Feb 11 '15 at 1:10
  • Also, [abc][abc]*, [abc]*[abc], and [abc]+ are all equivalent. – Scott Feb 11 '15 at 4:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.