0

こんにちは私は正規表現が大きな文字列内の1つまたは複数のサブ文字列がのようないくつかの基準に一致することを見つけることを望みます。

   "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

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

正規表現は、「[」と「]」の間のすべての文字と一致します。パターン。+?このことを貪欲にしないことを意味します。「]」が一致すると、この部分は終了します。それ以外の場合、[。*]を使用すると、マッチングは[switches......parts]を返します。

于 2012-09-10T10:49:46.160 に答える