I'm looking for some regex for this kind of strings
rgb(r,g,b)
rgba(r,g,b,a)
hsl(h,s%,l%)
hsla(h,s%,l%,a)
with:
r,g,b integer included between 0 and 255,
a float between 0 and 1 (truncated to first digit after the point)
h integer included between 0 and 359
s,l integer included between 0 and 100
For rgb, I wrote those regex:
rgb\(\s*((?:[0-2]?[0-9])?[0-9])\s*,\s*((?:[0-2]?[0-9])?[0-9])\s*,\s*((?:[0-2]?[0-9])?[0-9])\s*\)$
It works, but it also allows strings like rgb(299,299,299). How can I make it more effective? What about rgba,hsl and hsla? Thanks
Finally I wrote these regex:
String keywords_color_regex = "^[a-z]*$";
String hex_color_regex = "^#[0-9a-f]{3}([0-9a-f]{3})?$";
String rgb_color_regex = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*\\)$";
String rgba_color_regex = "^rgba\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%?\\s*,\\s*((0.[1-9])|[01])\\s*\\)$";
String hsl_color_regex = "^hsl\\(\\s*(0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d)\\s*,\\s*((0|[1-9]\\d?|100)%)\\s*,\\s*((0|[1-9]\\d?|100)%)\\s*\\)$";
I'm developing a library for my personal use, so I prefer to use regex. I fully commented the code. Thanks for the tips!
I can see two solutions for you. Either :
if
conditionsa) Regex
rgb\(\s*(?:(\d{1,3})\s*,?){3}\)
b) Visual description
a) Regex
rgb\(\s*(?:(?:\d{1,2}|1\d\d|2(?:[0-4]\d|5[0-5]))\s*,?){3}\)$
rdb(0,0,255) => OK
rdb(104,10,299) => KO
rdb(299,5,299) => KO
b) Visual description
Tips :
Regex allowing integer included between 0 and 359
\d{1,2}|[1-2]\d{2}|3[0-5]\d
Regex allowing integer included between 0 and 100
\d{1,2}|100
As a general rule of thumb, for the maintainability of the code prefer the solution #1. A developer not involved in regular expression would understand quite quickly what's going on. Don't forget to fully comment the code.
If you prefer solution #2 then be prepared to have developers with a good background in regular expression as the regular expression is complex.
Hex
/[\#]([a-fA-F\d]{6}|[a-fA-F\d]{3})/gm
RGB
/[Rr][Gg][Bb][\(](((([\d]{1,3})[\,]{0,1})[\s]*){3})[\)]/gm
RGBA
/[Rr][Gg][Bb][Aa][\(](((([\d]{1,3}|[\d\.]{1,3})[\,]{0,1})[\s]*){4})[\)]/gm
HSL
/[Hh][Ss][Ll][\(](((([\d]{1,3}|[\d\%]{2,4})[\,]{0,1})[\s]*){3})[\)]/gm
HSLA
/[Hh][Ss][Ll][Aa][\(](((([\d]{1,3}|[\d\%]{2,4}|[\d\.]{1,3})[\,]{0,1})[\s]*){4})[\)]/gm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With