I've read somewhere today that regex tag in SO gets most "give me ze code" type questions, so I was cautious in asking... I tried, but if this is a duplicate please let me know so I can delete.
[First]sometext[Second]
I would like to use Regex in Ruby to return value between second []:
Second
I so far have:
(?<=\[)(.*)(?=\])
which returns
First]sometext[Second
\[.*?(\[)
this grouping will return
[First]sometext[
so I've been struggling to somehow mix the two but no luck.. hope someone can help.
The closest reference I can find in SO was searched with "match second or nth occurence in regex" which I couldn't get it to work on my issue.
my workaround was to use gsub to replace the [First] with "" to the initial string with:
\[(.*?)\]
and then do another match.. but I would like know how it can be done with on regex usage.
> s = "ipsum[First]sometext[Second]lorem"
=> "ipsum[First]sometext[Second]lorem"
> s =~ /\[.*?\].*?\[(.*?)\]/
=> 5
> $1
=> "Second"
Why not use a greedy search at the beginning .* so capture as much as possible?
^.*\[(.*?)\]
Demo
You could then make it un-greedy (to capture only the stuff in the first [...] block) by appending ? as ^.*?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With