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

1
  • 1
    Any combo of letters and numbers can precede the "-". Commented Aug 3, 2011 at 0:30

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

ProTip™: Use gsub if you want to replace ALL occurrences.
6

You can also remove the first occurrence of a pattern with the following snippet:

s[/^WBA - /] = ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.