如何使用 Ruby 中的另一个字符串来分割一个字符串?
假设我有一个类似于以下的句子:
The quick brown fox jumps over the lazy dog
我想切掉之前的所有内容并包括“跳跃”,所以我留下:
over the lazy dog
当前,我获取了我想要删除的部分的索引,然后添加该部分的长度,然后对其进行切片,如下所示:
sentence = "The quick brown fox jumps over the lazy dog"
slice_index = sentence.index("jumps").to_i + sentence.size
sliced_sentence = sentence.slice(slice_index..-1)
是否有更好的方法来实现此目的?
谢谢!
Say I have a sentence similar to the following:
The quick brown fox jumps over the lazy dog
I'd like to slice off everything before and including "jumps", so I am left with:
over the lazy dog
Currently, I get the index of the part I'd like to remove, then add the length of that part to it, and then slice it, as such:
sentence = "The quick brown fox jumps over the lazy dog"
slice_index = sentence.index("jumps").to_i + sentence.size
sliced_sentence = sentence.slice(slice_index..-1)
Is there a better way of achieving this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我个人而言,我喜欢正则表达式解决方案,但是
sentence.split(" Jumps ").last也可以工作。
即使有多个“跳转”,
Personally, I like the regex solution, but
sentence.split(" jumps ").last
works too, even if there are multiple "jumps".
您可以使用正则表达式:
jump
是您要查找的单词,(.*)$
是字符串末尾之前的所有内容,括号表示第一个捕获组(因此被称为 $1)You could use a regular expression:
jump
is the word you are looking for,(.*)$
is everything until the end of the string and the brackets represent the first capturing group (which is therefore referenced as $1)也许不是最好的解决方案,但我会这样做:
split 根据分隔符将 str 分成子字符串,返回这些子字符串的数组。数组索引 1 始终是分隔符之后的部分。如果有多个“跳跃”,则会中断
Perhaps not the best solution but I would do it like so:
split divides str into substrings based on a delimiter, returning an array of these substrings. array index 1 will always be the section after the delimiter. This breaks if there are more than one " jumps "