Ruby global match regexp?

后端 未结 3 1260
终归单人心
终归单人心 2020-12-08 03:42

In other languages, in RegExp you can use /.../g for a global match.

However, in Ruby:

\"hello hello\".match /(hello)/

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 04:23

    Here's a tip for anyone looking for a way to replace all regex matches with something else.

    Rather than the //g flag and one substitution method like many other languages, Ruby uses two different methods instead.

    # .sub — Replace the first
    "ABABA".sub(/B/, '') # AABA
    
    # .gsub — Replace all
    "ABABA".gsub(/B/, '') # AAA
    

提交回复
热议问题