Topic: Pattern Matching with String#slice!


    I'm trying to grab substrings that match a regular expression using the slice method.  Suppose I have a string that is the following:

str = "<hello>blahblahblah</hello>yayayahahah<hello>yammeryammer</hello>

    I would like to grab the data enclosed by first set of <hello>...</hello> tags.  If I do something like this:

sl = str.slice! /<hello>.*</hello>/

    it will return the entire string rather than the first set.  It appears that the slice! method will return the largest string that matches the pattern, when I want it to match the smallest string that matches the pattern.  Is there any way to do this?



Re: Pattern Matching with String#slice!

This is just how regular expressions behave, they call it greediness. smile

To change this behavior, you can end the search pattern with a question mark (.*?) which will make it non-greedy. Then it should select what you want.

sl = str.slice /<hello>.*?</hello>/

Railscasts - Free Ruby on Rails Screencasts

Re: Pattern Matching with String#slice!

This works !!!  Thanks ...