这是我的代码行:
col_value = line_item[column].scan(/\d+./).join().to_i
当我在文本字段中输入30,000时,col_value为30。 我希望它带来任何数字: 30000 30.5 30.55 30000
任何这些都是有效的......
扫描和/或连接是否有问题导致它返回30?使用下面建议的正则表达式仍然可以重新启动30,例如
col_value = line_item[column].scan(/\d+[,.]?\d+/).join().to_i
可能是“to_i
”将“30,000”转换为30 ??
答案 0 :(得分:1)
此正则表达式将匹配您所需的输出:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 col-md-3 col-lg-3 servicesub" id="servicesub" >
<ul>
<li class="servicesubitem">
<span class="subitem">Communications
<br>
& Airtime</span><span class="fa1 fa-phone"> </span>
</li>
<div class="servicesubli">
<ul>
<li>
VSAT
</li>
<li>
IRIDIUM
</li>
<li>
GSM
</li>
<li>
INMARSAT
</li>
<li>
IDIRECT
</li>
</ul>
</div>
<li class="servicesubitem">
<span class="subitem">IT &
<br>
Networking</span><span class="fa1 fa-sitemap"> </span>
</li>
<div class="servicesubli">
<ul>
<li>
Built/Refit Consultancy
</li>
<li>
Managed IT Support
</li>
<li>
Networking (Wired & Wireless)
</li>
<li>
Backup & Disaster Recovery
</li>
<li>
Antivirus
</li>
</ul>
</div>
</ul>
</div>
<div id="serviceinfo">
</div>
<div style ="clear:both;"></div>
<div id = "footer">
</div>
此处\d+[,.]?\d*
用作匹配的可选项。
答案 1 :(得分:1)
\d+(?:[,.]\d+)?
试试这个。这应该为你做。
答案 2 :(得分:0)
是的,"30,000".to_i #=> 30"
。请参阅String#to_i:“忽略有效数字末尾之外的无关字符。”
我建议您先删除逗号,然后应用正则表达式:
R = /
\d+ # match >= 0 digits
| # or
\d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
/x # extended mode
str = "30,000 30.5 30.55 30000 1. .1"
str1 = str.tr(',','')
#=> "30000 30.5 30.55 30000 1. .1"
a = str1.scan(R)
#=> ["30000", "30", "5", "30", "55", "30000"]
a.map(&:to_i)
#=> [30000, 30, 5, 30, 55, 30000]
链接后,我们有:
str.tr(',','').scan(R).map(&:to_i)
如果是所需的解决方案:
#=> [30000, 30, 5, 30, 55, 30000, 1, 0]
正则表达式需要修改如下:
R = /
\d+ # match >= 0 digits
| # or
\d+\.\d+ # match > 0 digits, a decimal point, then > 0 digits
| # or
\d+\. # match > 0 digits, then a decimal point
| # or
\.\d+ # match a decimal point, then > 0 digits
/x # extended mode