Ruby 全局匹配正则表达式? [英] Ruby global match regexp?

查看:55
本文介绍了Ruby 全局匹配正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他语言中,在 RegExp 中,您可以使用 /.../g 进行全局匹配.

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

然而,在 Ruby 中:

However, in Ruby:

"hello hello".match /(hello)/

只捕获一个你好.

如何捕获所有hello?

推荐答案

可以使用扫描方式.scan 方法要么给你一个所有匹配的数组,要么,如果你传递一个块,将每个匹配传递给块.

You can use the scan method. The scan method will either give you an array of all the matches or, if you pass it a block, pass each match to the block.

"hello1 hello2".scan(/(hello\d+)/)   # => [["hello1"], ["hello2"]]

"hello1 hello2".scan(/(hello\d+)/).each do|m|
  puts m
end

我已经写过关于这个方法的文章,你可以在这里阅读它 接近文章结尾.

I've written about this method, you can read about it here near the end of the article.

这篇关于Ruby 全局匹配正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆