Alex Rivera | Logout

Ruby - remove pattern from string

Asked 2011-08-03T00:16:43.487
29

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".

Edit
Report

2 Answers

48

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.

answered 2011-08-03T00:18:03.333
17

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

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
answered 2011-08-03T00:23:11.957

Your Answer