RegEx for distance in metric system

2019-06-22 04:05发布

I want a RegEx to match distance values in metric system. This regex should match 12m, 100cm,1km ignoring white space

3条回答
何必那么认真
2楼-- · 2019-06-22 04:38

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

(\d+).?(\d*)\s*(m|cm|km)
查看更多
乱世女痞
3楼-- · 2019-06-22 04:40

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.

查看更多
趁早两清
4楼-- · 2019-06-22 04:43

Try this:

(?:0|[1-9]\d*)\s*(?:da|[yzafpnμmcdhkMGTPEZY])?m
查看更多
登录 后发表回答