Regular expression to find one or more than one substring inside big string

Hi i want regular expression to find one or more than one substrings inside big string match some criteria like.

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

the result should be like these substrings

         switches,allow,parts

and in this case

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

result should be the only "switches"

Thanks in advance.

Answers


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

The Regexp will match any chars between '[' and ']'. The pattern .+? means NOT do this thing greedy. When a "]" is matched, this part is over. Otherwise, if we use [.*] , the matching will return [switches......parts].


Need Your Help

calling a Timer from inside an ActionListener in Java

swing timer java

I have created a (2nd) Timer in Java but rather than adding the arguements (int, action) when creating the Timer, I am trying to initialize the Timer inside an actionlistener.

launch app, capture stdout and stderr in c++

c++ process stdout capture launch

How do I launch an app and capture the output via stdout and maybe stderr?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.