查找字符串中的第一个小数

时间:2018-06-05 15:43:33

标签: ruby

我有两个由两个数字组成的字符串。我试图将它们分成两个子串,以便每个小数后有两个小数位。

我有这段代码:

 <!--
         The initialization ContentProvider will call FacebookSdk.sdkInitialize automatically
         with the application context. This config is merged in with the host app's manifest,
         but there can only be one provider with the same authority activated at any given
         point; so if the end user has two or more different apps that use Facebook SDK, only the
         first one will be able to use the provider. To work around this problem, we use the
         following placeholder in the authority to identify each host application as if it was
         a completely different provider.
        -->

    <provider android:authorities="${applicationId}.FacebookInitProvider" android:exported="false" android:name="com.facebook.internal.FacebookInitProvider" />

它可以处理八位数的字符串: if homeodds.length == 10 then homeoddsp = homeodds[0,5].to_f bookieh = homeodds[5,5].to_f else homeoddsp = homeodds[0,4].to_f bookieh = homeodds[4,4].to_f end 转换为"1.211.90""1.21"

十个数字字符串也有效: "1.90"转换为"12.2113.00""12.21"

当我有一个九位数的字符串,如"13.00""9.1110.00"时,我需要找出第一个小数的位置,然后取两位数,以便余数成为第二个子串。这些情况,我不能一直这样做。

1 个答案:

答案 0 :(得分:4)

您可以使用String#scan来解决此特定问题

def decimal_splits(string)
  string.scan(/\d+\.\d{2}/)
end

分解正则表达式:

  • \d+一位或多位数字
  • \.小数点
  • \d{2}两位数字

结果将是表达式的匹配数组。

decimal_splits("9.1110.00")
#=> ["9.11", "10.00"]
decimal_splits("12.2113.00")
#=> ["12.21", "13.00"]
decimal_splits("1.211.90")
#=> ["1.21", "1.90"]
decimal_splits("10.119.55")
#=> ["10.11", "9.55"]