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,"")
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.
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.
=~ 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.
You need to use "\n" not '\n' in your gsub.
Without regular expression:
"yellow-corn-(corn-on-the-cob)".delete('()') #=> "yellow-corn-corn-on-the-cob"
Try this:
clean_string = old_string.gsub(/[()]/, "")
On a side note, Rubular is awesome to test your regular expressions quickly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With