0

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

   "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.

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

提前致谢。

4

1 回答 1

3

你需要字符串#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 将匹配 '[' 和 ']' 之间的任何字符。模式 .+? 意味着不要贪婪地做这件事。当匹配一个“]”时,这部分就结束了。否则,如果我们使用 [.*] ,匹配将返回 [switches......parts]。

于 2012-09-10T10:49:46.160 回答