Regular expressions for float values and coordinates
I was working with some pixel values the other day and I had this problem; I’m getting an RGBA value from my object model but it returns it on a string format (ie: 0, 1, 1, .5). For this specific task I only cared about the alpha value so I figured writing a regular expression for it should be the easiest way to do this and I was in for a fun surprise.
So I started out with this:
\d,\s\d,\s\d,\s\d
Wrong!! – I forgot one cardinal rule about regular expressions, they work against string content so a decimal will not be considered part of a number. So long story short what I thought should be a simple regular expression turned into a scary one (at some point I should have given up on it and used String.Split but where would the fun in that be?). So here’s the final version of it:
\d+(\.\d*)?,\s\d+(\.\d*)?,\s\d+(\.\d*)?,\s(?<alpha>\d+(\.\d*)?)
A breakdown of that expression
\d+(\.\d*)? – This will pick up my values, it will pick up both 1 and 1.0
,\s – This is the separator which in my case is always a comma followed by a space
(?<alpha>\d+(\.\d*)?) – This is the same as the first part except that I defined this group as alpha so that I could pull the value. I
And a snippet of the code where it would be used (I defined groups for all 4 values here:
Regex exp = new Regex(@"(?<red>\d(\.\d*)?),\s(?<green>\d(\.\d*)?),\s(?<blue>\d(\.\d*)?),\s(?<alpha>\d(\.\d*)?)"); // Get this value from somewhere string value = ... Match match = exp.Match(value); string alpha = match.Result("${alpha}"); // Do some comparison with your alpha value … |
Similar expressions can be used for coordinates (both 2D and 3D)
2D : (3.1,23,5) = \((?<X>\d(\.\d*)?),(?<Y>\d(\.\d*)?)\)
3D : (3.1,23,5,90) = \((?<X>\d(\.\d*)?),(?<Y>\d(\.\d*)?),(?<Z>\d(\.\d*)?)\)
Comments
- Anonymous
March 10, 2011
oh,the article gives inspiration,I would picked it up.Regular expressions are boring me for a long time .