RegEx for distance in metric system
Question
I want a RegEx
to match distance values in metric system. This regex should match 12m
, 100cm
,1km
ignoring white space
Solution
And to extend Paul's answer to include decimal place values...
(\d+).?(\d*)\s*(m|cm|km)
OTHER TIPS
Try this:
(?:0|[1-9]\d*)\s*(?:da|[yzafpnμmcdhkMGTPEZY])?m
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.