使用括号rails从字符串中捕获所有关键字

时间:2018-04-24 13:08:14

标签: ruby

我想从哈希下面的字符串中捕获所有出现的关键字。

str = "Coming this week for [CurrentCourseName] chapter [Chaptername] of interesting event [EventName]"

必填项:

["CurrentCourseName", "Chaptername", "EventName"]

1 个答案:

答案 0 :(得分:3)

您只需要将scan方法与正则表达式一起使用:

str.scan(/\[(.*?)\]/).flatten

实际输出:

2.2-head :001 > str = "Coming this week for [CurrentCourseName] chapter [Chaptername] of interesting event [EventName]"
 => "Coming this week for [CurrentCourseName] chapter [Chaptername] of interesting event [EventName]" 
2.2-head :002 > str.scan(/\[(.*?)\]/).flatten
 => ["CurrentCourseName", "Chaptername", "EventName"]