开发者

Ruby - remove pattern from string

开发者 https://www.devze.com 2023-03-24 14:19 出处:网络
I have a strin开发者_如何转开发g pattern that, as an example, looks like this: WBA - Skinny Joe vs. Hefty Hal

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 - /] = ''
0

精彩评论

暂无评论...
验证码 换一张
取 消