Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip parenthesis from a string in Ruby?

Tags:

string

regex

ruby

I have a string, like this:

"yellow-corn-(corn-on-the-cob)"

and I would like to strip the parenthesis from the string to get something like this:

"yellow-corn-corn-on-the-cob"

I believe you would use gsub to accomplish this, but I'm not sure what pattern I would need to match the parenthesis. Something like:

clean_string = old_string.gsub(PATTERN,"")
like image 517
rps Avatar asked Sep 24 '11 15:09

rps


People also ask

How do you remove parentheses from a string?

To remove parentheses from string using Python, the easiest way is to use the Python sub() function from the re module. If your parentheses are on the beginning and end of your string, you can also use the strip() function.

How do I remove special characters from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do you get rid of the N at the end of a string in Ruby?

You need to use "\n" not '\n' in your gsub.


2 Answers

Without regular expression:

"yellow-corn-(corn-on-the-cob)".delete('()') #=> "yellow-corn-corn-on-the-cob"
like image 150
steenslag Avatar answered Nov 02 '22 08:11

steenslag


Try this:

clean_string = old_string.gsub(/[()]/, "")

On a side note, Rubular is awesome to test your regular expressions quickly.

like image 34
Benoit Garret Avatar answered Nov 02 '22 10:11

Benoit Garret