Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby regex match from end of string

Tags:

regex

ruby

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.

like image 697
Rok Avatar asked Mar 14 '26 04:03

Rok


2 Answers

> s = "ipsum[First]sometext[Second]lorem"
=> "ipsum[First]sometext[Second]lorem"
> s =~ /\[.*?\].*?\[(.*?)\]/
=> 5
> $1
=> "Second"
like image 127
Philip Hallstrom Avatar answered Mar 17 '26 02:03

Philip Hallstrom


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 ^.*?.

like image 42
OnlineCop Avatar answered Mar 17 '26 02:03

OnlineCop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!