正则表达式,用于在大字符串中查找一个或多个子字符串

时间:2012-09-10 10:42:12

标签: ruby regex

您好我希望正则表达式在大字符串中找到一个或多个子字符串匹配某些条件,例如。

   "I have done my best to document all the [switches] and characters that I can  locate.Regular expressions [allow] you to group like [parts] of the substring into"

结果应该像这些子串一样

         switches,allow,parts

,在这种情况下

      "I have done my best to document all the [switches] and character.

结果应该是唯一的“开关”

提前致谢。

1 个答案:

答案 0 :(得分:3)

你需要String#scan:

str = "I have done my best to document all the [switches] and characters that I can  locate.Regular expressions [allow] you to group like [parts] of the substring into"
str.scan /\[.+?\]/   # => ["[switches]", "[allow]", "[parts]"]
# or use lookahead and lookbehind pattern
str.scan /(?<=\[).+?(?=\])/ # => ["switches", "allow", "parts"]

Regexp将匹配&#39; [&#39;和&#39;]&#39;。模式。+?意味着不要把这件事贪得无厌。当一个&#34;]&#34;匹配,这部分结束了。否则,如果我们使用[。*],匹配将返回[开关......部分]。