如何使用 Ruby 中的另一个字符串来分割一个字符串?

发布于 2024-11-26 02:49:13 字数 452 浏览 2 评论 0原文

假设我有一个类似于以下的句子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里的微风 2024-12-03 02:49:13

就我个人而言,我喜欢正则表达式解决方案,但是

sentence.split(" Jumps ").last也可以工作。

即使有多个“跳转”,

Personally, I like the regex solution, but

sentence.split(" jumps ").last

works too, even if there are multiple "jumps".

夜还是长夜 2024-12-03 02:49:13

您可以使用正则表达式:

sentence =~ /jumps(.*)$/
sliced_sentence = $1
#=> " over the lazy dog"

jump 是您要查找的单词,(.*)$ 是字符串末尾之前的所有内容,括号表示第一个捕获组(因此被称为 $1)

You could use a regular expression:

sentence =~ /jumps(.*)$/
sliced_sentence = $1
#=> " over the lazy dog"

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)

沐歌 2024-12-03 02:49:13

也许不是最好的解决方案,但我会这样做:

sentence = "The quick brown fox jumps over the lazy dog"
sentence.split(" jumps ")[1]

split 根据分隔符将 str 分成子字符串,返回这些子字符串的数组。数组索引 1 始终是分隔符之后的部分。如果有多个“跳跃”,则会中断

Perhaps not the best solution but I would do it like so:

sentence = "The quick brown fox jumps over the lazy dog"
sentence.split(" jumps ")[1]

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 "

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文