开发者

Match as to the right as possible using =~ (regex)

I'm trying to get this to work:

data = "Testing: Download complete (This is a string) - Priority 0 Some random value Testing: Download complete (This to) - Priority 0 Another random value"
puts $1 if data =~ /Testing: Download complete \((.*?)\) - Priority.*?$/i

I want to print This开发者_C百科 to, right now This is a string is being printed.

The idea is to get the value as far as to the right as possible.


Use

puts $1 if data =~ /.*Testing: Download complete \((.*?)\) - Priority/i

The initial .* will match until the end of the line, and the rest of the regex will backtrack as much as needed to match. Therefore, the last possible match will be found.


If you just want to get the furthest brackets, no need to use regular expression

>> data
=> "Testing: Download complete (This is a string) - Priority 0 Some random value Testing: Download complete (This to) - Priority 0 Another random value"
>> data.split(")")[-2].split("(")[-1]
=> "This to"
>>

When you split the string on ")", the last 2nd element will contain what you want. Get that, and split on "(". The last element will be your final output. Not everything needs to be solved using regex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜