Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - remove pattern from string

Tags:

string

regex

ruby

I have a string pattern that, as an example, looks like this:

WBA - Skinny Joe vs. Hefty Hal 

I want to truncate the pattern "WBA - " from the string and return just "Skinny Joe vs. Hefty Hal".

like image 410
keruilin Avatar asked Aug 03 '11 00:08

keruilin


People also ask

How do you remove something 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.

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

Delete - (. Delete is the most familiar Ruby method, and it does exactly what you would think: deletes a sub-string from a string. It will search the whole string and remove all characters that match your substring. The downside of delete is that it can only be used with strings, not RegExs.

How do you remove spaces from a string in Ruby?

If you want to remove only leading and trailing whitespace (like PHP's trim) you can use . strip , but if you want to remove all whitespace, you can use . gsub(/\s+/, "") instead .

How do you replace multiple characters in a string in Ruby?

Since Ruby 1.9. 2, String#gsub accepts hash as a second parameter for replacement with matched keys. You can use a regular expression to match the substring that needs to be replaced and pass hash for values to be replaced.


2 Answers

Assuming that the "WBA" spot will be a sequence of any letter or number, followed by a space, dash, and space:

str = "WBA - Skinny Joe vs. Hefty Hal" str.sub /^\w+\s-\s/, '' 

By the way — RegexPal is a great tool for testing regular expressions like these.

like image 85
Jon Gauthier Avatar answered Sep 20 '22 04:09

Jon Gauthier


If you need a more complex string replacement, you can look into writing a more sophisticated regular expression. Otherise:

Keep it simple! If you only need to remove "WBA - " from the beginning of the string, use String#sub.

s = "WBA - Skinny Joe vs. Hefty Hal" puts s.sub(/^WBA - /, '') # => Skinny Joe vs. Hefty Hal 
like image 35
maček Avatar answered Sep 23 '22 04:09

maček