如何使用Ruby删除字符串中特定字符之后的子字符串?
如何使用Ruby删除字符串中特定字符之后的子字符串?
new_str = str.slice(0..(str.index('blah')))
new_str = str.slice(0..(str.index('blah') + 'blah'.length))
- mvndaai我发现"Part1?Part2".split('?')[0]
更易于阅读。
我很惊讶没有人建议使用'gsub'
irb> "truncate".gsub(/a.*/, 'a')
=> "trunca"
使用 gsub 的感叹号版本可以修改字符串。
/(?<=a).*/
或者 /a\K.*/
,以排除匹配到的 "a"
? - Cary Swoveland如果您有多个相同字符的出现,并且希望从最后一次出现到结尾删除(而不是第一个), 那么这就是一个特殊情况。
按照Jacob的建议,您只需使用rindex
而不是index
,因为rindex
获取字符串中字符的索引,但是从末尾开始。
像这样:
str = '/path/to/some_file'
puts str.slice(0, str.index('/')) # => ""
puts str.slice(0, str.rindex('/')) # => "/path/to"
str = "Hello World"
stopchar = 'W'
str.sub /#{stopchar}.+/, stopchar
#=> "Hello W"
我们也可以使用partition
和rpartition
,具体取决于我们想要使用指定字符的第一个还是最后一个实例:
string = "abc-123-xyz"
last_char = "-"
string.partition(last_char)[0..1].join #=> "abc-"
string.rpartition(last_char)[0..1].join #=> "abc-123-"