ruby - 如何替换 ruby​​ 中模式的每个实例?

标签 ruby regex string replace

string.sub 看起来它只替换了第一个实例。是否有可以替代所有模式的选项或其他方法?你能在 perl 之类的正则表达式中完成吗?

(我觉得像 r/blah/blah/)

... 并 +1 给任何能告诉我为什么 string.sub 只替换第一个匹配项的人?

最佳答案

String.gsub应该可以解决问题。

引用文档:

gsub(pattern, replacement) → new_str

Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. \\d will match a backlash followed by d, instead of a digit.

关于ruby - 如何替换 ruby​​ 中模式的每个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1895295/

相关文章:

ruby - 如何通过 API 从 Hipchat 获取房间的所有消息历史记录?

regex - 需要正则表达式以单引号或双引号解析关键字='value'

c# - 需要从c#中的字符串中提取列名

javascript - 我如何在这个正则表达式中自己编写一种转义字符?

c++ - 从字符串中提取值 C++

ruby-on-rails - Ruby 1.87 与 1.92 Date.parse

ruby - float 和符号如何具有直接值(value)?

ruby - 如何在 Ruby 中自动将类实例转换为 Float?

python - 如何从不包括一个变量的字符串列表中创建一个新的字符串列表?

java - 如何打印数组?