【问题标题】:Replace only the integers in a string with gsub仅用 gsub 替换字符串中的整数
【发布时间】:2021-09-27 14:43:03
【问题描述】:

我试图去掉这个字符串中的整数,但保留浮点数。我已经在网上尝试了下面的正则表达式并突出显示了正确的部分,但注意到我使用 gsub 时会发生

tops = "17500 dw.sapAGZ_D00 pf=/usr/sap/A  8.0 17488 dw.sapAGZ_D00 pf=/usr/sap/A  7.1 17489 dw.sapAGZ_D00 pf=/usr/sap/A  7.0 17493 dw.sapAGZ_D00 pf=/usr/sap/A  5.9 17490 dw.sapAGZ_D00 pf=/usr/sap/A  5.7 17495 dw.sapAGZ_D00 pf=/usr/sap/A  5.4 17499 dw.sapAGZ_D00 pf=/usr/sap/A  5.0 17480 dw.sapAGZ_D00 pf=/usr/sap/A  4.3 17492 dw.sapAGZ_D00 pf=/usr/sap/A  4.0"

tops.gsub(/(?<=\s|^)\d+(?=\s|$)/, '--- ')

puts tops ;

【问题讨论】:

  • 你可以试试gsub!,它执行String#gsub的替换。

标签: regex ruby gsub


【解决方案1】:

您的搜索模式很好(对于特定的输入 - 例如,我猜它不会正确处理负整数),但 gsub 只是不会更改接收器(原始字符串) - 它返回一个新的所有的替换。

所以要么使用gsub!,或者如果您也需要原始字符串,则将字符串重新分配给另一个变量。

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 2021-10-30
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多