如果您真正要问的是各种字符串的模式匹配,请查看使用scan
并获取数字字符串:
[
"Service charges: 10 Total: 100 Shipping: 10",
"Service charges: 10 Total Amount: 100 Shipping: 10",
"Service charges: 10 Grand Total: 100 Shipping: 10",
"Service charges: 10 Total Amount (Rs.): 100 Shipping: 10",
].map{ |s| s.scan(/\d+/)[1] }
=> ["100", "100", "100", "100"]
这假设您想要每个字符串中的第二个数字。
如果该订单要更改,这不太可能,因为您看起来正在扫描发票,那么模式和/或的变化scan
将起作用。这会将其切换并使用基于“Total”位置的标准正则表达式搜索,一些可能的中间文本,后跟“:”和总值:
[
"Service charges: 10 Total: 100 Shipping: 10",
"Service charges: 10 Total Amount: 100 Shipping: 10",
"Service charges: 10 Grand Total: 100 Shipping: 10",
"Service charges: 10 Total Amount (Rs.): 100 Shipping: 10",
].map{ |s| s[/Total.*?: (\d+)/, 1] }
=> ["100", "100", "100", "100"]
要to_i
在map
语句中附加整数值:
[
"Service charges: 10 Total: 100 Shipping: 10",
"Service charges: 10 Total Amount: 100 Shipping: 10",
"Service charges: 10 Grand Total: 100 Shipping: 10",
"Service charges: 10 Total Amount (Rs.): 100 Shipping: 10",
].map{ |s| s[/Total.*?: (\d+)/, 1].to_i }
=> [100, 100, 100, 100]
对于您的示例字符串,最好使用区分大小写的模式来匹配“Total”,除非您知道您会遇到小写的“total”。而且,在这种情况下,你应该展示这样一个例子。