How to remove parentheses and the text inside them from a string in Ruby

1 Answer

0 votes
# Remove all parentheses and the text inside them.
#
# @param text [String] The input string
# @return [String]     The cleaned string
def remove_parentheses_with_content(text)
  # Remove parentheses and everything inside them
  cleaned = text.gsub(/\([^)]*\)/, " ")

  # Collapse multiple spaces into one
  cleaned = cleaned.split.join(" ")

  # Final trim of leading/trailing spaces
  cleaned.strip
end

str = "(An) API (API) (is a) (connection) connects (between) computer programs"
output = remove_parentheses_with_content(str)

puts output



=begin
run:

API connects computer programs

=end

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...