I want a RegEx to match distance values in metric system. This regex should match 12m, 100cm,1km ignoring white space
+4
A:
As you didn't specify exactly what you wanted, I used your examples to derive that you want find an integer value, followed by optional whitespace, followed by a unit specifier of cm, m or km. So - this is the simplest example of that.
/(\d+)\s*(m|cm|km)/
The first parentheses captures the number, then it skips 0-many whitespace chars before capturing your required units in the second set of parentheses.
As you can see in other answers, you can go beyond this to pick up decimal values, and also capture a wider number of SI unit prefixes too.
Paul Dixon
2009-09-27 10:29:13
but this will not work for 12m 20cm
2009-09-27 10:50:23
Freeman: Do you normally notate distances that way? `12.2 m` is a much more natural way to say it..
kaizer.se
2009-09-27 11:14:36
first thought the `yzafpnμmcdhkMGTPEZY` part was a joke, those are the SI-prefixes! :-)
kaizer.se
2009-09-27 11:15:27
And don't forget the additional 'quantifiers' proposed in a 1993 update to the Jargon File (http://catb.org/~esr/jargon/html/Q/quantifiers.html), namely, groucho/grouchi and harpo/harpi. It wasn't suggested how the conflict between G = Giga (1e9) and G = Grouchi (1e30) could be resolved.
pavium
2009-09-27 11:24:00
+7
A:
And to extend Paul's answer to include decimal place values...
(\d+).?(\d*)\s*(m|cm|km)
NickLarsen
2009-09-27 10:35:42
Good point, though I've tried to produce the simplest regex that matches the general pattern of his examples - integer values of centimetres, metres and kilometres.+1 - welcome to stackoverflow :)
Paul Dixon
2009-09-27 10:39:00
I did the same originally, but when you beat me to the post, I figured I would extend it :), thanks for the welcome.
NickLarsen
2009-09-27 10:43:53