string.sub
看起来只替换第一个匹配项。是否有此选项或其他可以替换所有模式的方法?您能否在正则表达式中像Perl一样做到这一点?
(我认为类似 r/blah/blah/ 的东西)
... 任何人能告诉我为什么 string.sub
只替换第一个匹配项吗?+1。
String.gsub 可以解决问题。
引用文档:
gsub(pattern, replacement) → new_str
返回 str 的一个副本,其中所有匹配 pattern 的子串都被第二个参数替换。pattern 通常是一个 Regexp;如果给定为 String,则会将其包含的任何正则表达式元字符解释为字面意义,例如
\\d
将匹配反斜杠后跟着的d
,而不是一个数字。
我可以解释为什么sub
只替换模式的第一个匹配项,但我认为文档做得更好(来自命令行上的ri String#sub
):
str.sub(pattern, replacement) => new_str
str.sub(pattern) {|match| block } => new_str
Returns a copy of _str_ with the _first_ occurrence of _pattern_
replaced with either _replacement_ or the value of the block.
g
修饰符来使替换全局化。替换全部通常是您想要的,但并不总是如此。 - Telemachus