rickyduck
rickyduck

Reputation: 4084

In ruby, get content in brackets

I have the following string:

Eclipse Developments (Scotland) Ltd t/a Martin & Co (Glasgow South)

I need to get the last (always the last, however sometimes the only) brackets value, so in this case "Glasgow South".

I know I should use .sub but can't work out the correct regex.

Upvotes: 3

Views: 5852

Answers (2)

Chowlett
Chowlett

Reputation: 46685

Regexps are greedy; if you ask for .* it will match as much as possible. For that reason, the following will work:

test = "Eclipse Developments (Scotland) Ltd t/a Martin & Co (Glasgow South)"
test =~ /.*\((.*)\)/
answer = $1
# => "Glasgow South"

Upvotes: 2

tadman
tadman

Reputation: 211740

Usually sub is used for sub-stitutions. What you need is scan:

test = "Eclipse Developments (Scotland) Ltd t/a Martin & Co (Glasgow South)"

test.scan(/\(([^\)]+)\)/).last.first
# => "Glasgow South"

The reason for the odd .last.first call is scan returns an array of arrays by default. You want the first (and only) element of the last match.

Translating that regexp, which can be prickly for the uninitiated:

\(     # A literal bracket followed by...
(      # (Memorize this)
[^)]+  # One or more (+) characters not in the set of: closing-bracket [^)]
)      # (End of memorization point)
\)     # ...and a literal closing bracket.

Upvotes: 22

Related Questions