简体   繁体   中英

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

这应该工作:

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

In case the sentence itself can contain parenthesis:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM