tags:

views:

162

answers:

3

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
but this will not work for 12m 20cm
Freeman: Do you normally notate distances that way? `12.2 m` is a much more natural way to say it..
kaizer.se
+10  A: 

Try this:

(?:0|[1-9]\d*)\s*(?:da|[yzafpnμmcdhkMGTPEZY])?m
Gumbo
first thought the `yzafpnμmcdhkMGTPEZY` part was a joke, those are the SI-prefixes! :-)
kaizer.se
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
ah this one is good. +1
Pavel Shved
+7  A: 

And to extend Paul's answer to include decimal place values...

(\d+).?(\d*)\s*(m|cm|km)
NickLarsen
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
I did the same originally, but when you beat me to the post, I figured I would extend it :), thanks for the welcome.
NickLarsen