On Tue, 18 Jan 2005 06:26:08 +0900, Zach Dennis <zdennis / mktec.com> wrote:
> trans. (T. Onoma) wrote:
> > Let me painfully honest: I hate parsing, especially w/ regexp, and I don't
> > care if it's because I stupid and suck at it. It shouldn't have to be this
> > hair pulling! Anyway... Can some one please give the regular expression to
> > match the first square bracket's contents. In this case it would be "Hello".
> >
> > s = <<-EOS
> > [Hello]
> > This [b]is[b.] a test.
> > [Hello.]
> > EOS
> 
> The trick here is to make sure you are non-greedy.
> 
> s =~ /\[([^\]]*)\]/

Or:

s =~ /\[.*?\]/

which uses the ? non-greedy modifier to ensure that only the very next
"]" is matched. For example:


str = <<EOT
[this] [is a test]
here are[some]brackets
[brackets ]
[] no words
no brackets
EOT
    ==>"[this] [is a test]\nhere are[some]brackets\n[brackets ]\n[] no
words\nno brackets\n"

str.each{|line| p line.scan(/\[.*?\]/)}
["[this]", "[is a test]"]
["[some]"]
["[brackets ]"]
["[]"]
[]

cheers,
Mark