Search code examples
phpregexalphapcrergba

Regex for alpha component or RGBA/HSLA, why I'm getting matching groups?


^(?:(?:0(:?\.[0-9])?)|(?:1(?:\.0)?))$

Should (i'm not a regex guru) match the alpha component of RGBA/HSLA (0, 0.0 to 0.9, 1, 1.0).

However when I use Rubular with this regex/test string I get a matching group of 1. with test string 1.0 and I get a matching group .9 with test string 0.9.

I don't need to capture groups... what I'am doing wrong?


Solution

  • You are getting groups for this:

    ^(?:(?:0(:?\.[0-9])?)|(?:1(?:\.0)?))$
             ^^ its a mistake i believe
    

    It should be:

    ^(?:(?:0(?:\.[0-9])?)|(?:1(?:\.0)?))$
             ^^
    

    :? means optional colon. So it always matches with your input. Whereas ?: means ignore group capture, which you are already using.