Ruby - remove pattern from string
I have a strin开发者_如何转开发g 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".
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.
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
You can also remove the first occurrence of a pattern with the following snippet:
s[/^WBA - /] = ''
精彩评论