user984621
user984621

Reputation: 48453

Ruby - how to get rid of the last element in a string according to the following pattern?

I have these kind of strings:

A regular sentence.
A regular sentence (United Kingdom).
A regular sentence (UK).

The goal is to remove the term in the brackets, thus the desired output would be:

A regular sentence.
A regular sentence.
A regular sentence.

How to achieve this in Ruby (probably with using regular expressions?)?

Thank you

Upvotes: 0

Views: 90

Answers (3)

hirolau
hirolau

Reputation: 13901

In case the sentence itself can contain parenthesis:

a = "A (very) regular sentence (UK)."
p a.gsub(/\s\([^()]*\)(?=\.\Z)/, '') #=> "A (very) regular sentence."

Upvotes: 0

Bala
Bala

Reputation: 11244

"A regular sentence (UK).".gsub(/\(.*\)/,"").strip #=> "A regular sentence ."

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

This should work:

string.gsub(/\s*\(.*\)/, '')

Upvotes: 3

Related Questions