简体   繁体   English

使用regexp匹配Ruby中的浮动

[英]Match floats in Ruby with regexp

I need to extract a float from a string in Ruby, but if I try to extract it with the normal \\d I of course don't fetch the digits in front of the ",". 我需要从Ruby中的字符串中提取浮点数,但是如果我尝试使用普通符号提取它,我当然不会获取“,”前面的数字。

"3,25 år -".match((\d+)\s?år\s?-)[1] => # "25"

Is there an easy way to fetch the whole number? 有没有一种简单的方法来获取整数?

"3,25 år -".match(/([\d,]+)\s?år\s?-/)[1] => # "3,25"

Pay attention that your code also had another error. 注意你的代码也有另一个错误。 You were missing the regex delimiters. 你错过了正则表达式分隔符。 It should be 它应该是

match(/.../)

not

match(...)

You are missing the forward slashes / around the regular expression. 您缺少正则表达式的正斜杠/周围。

Apart of that, this will return what you want: 除此之外,这将返回你想要的:

"3,25 år -".match(/(\d+(?:,\d+)?)\s?år\s?-/)[1] => # "3,25"

As a side note, the above will match both positive integers and floats. 作为旁注,上面将匹配正整数和浮点数。 If you are sure you will always have floats, simplify it like that: 如果您确定您将始终拥有浮动,请将其简化为:

"3,25 år -".match(/(\d+,\d+)\s?år\s?-/)[1] => # "3,25"

Finally, I would propose you to get used to the [0-9] notation for digits instead of \\d , ready why here , so finally try this: 最后,我建议你习惯于[0-9]表示数字而不是\\d为这里准备好 ,所以最后试试这个:

"3,25 år -".match(/([0-9]+,[0-9]+)\s?år\s?-/)[1] => # "3,25"

PS. PS。 I would suggest you to avoid the [\\d,]+ solutions since this regular expression can match also non-numbers, eg it will match 1,,1 or 1, or ,1 . 我建议你避免[\\d,]+解决方案,因为这个正则表达式也可以匹配非数字,例如它将匹配1,,11,,1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM