【问题标题】:Remove everything after some characters删除某些字符后的所有内容
【发布时间】:2017-08-26 02:37:01
【问题描述】:

我有两种情况:

首先,我可能有这样的字符串:

  Posted 03-20-2017 More info Go to Last Post

我可能有这样的字符串:

  Posted today More info Go to Last Post

在这两种情况下,我都不想要更多信息...

我尝试使用gsub,但这两种情况都不起作用。有人有可能的解决方案吗?

【问题讨论】:

  • 您应该使用gsub 发布您尝试过的内容。你能澄清一下你想提取字符串的哪一部分吗?我认为您想要“2017 年 3 月 20 日发布”或“今天发布”。

标签: ruby string methods


【解决方案1】:

这可以通过在您的字符串上运行split("More info") 相对容易地完成。它的作用是将字符串分解成一个数组,如下所示:

new_string  = "Posted today More info Go to Last Post"
new_string = new_string.split("More info")
# becomes ["Posted today ", " Go to Last Post"]

split 的作用是将字符串拆分为一个数组,其中每个元素都是参数之前的元素。所以如果你有"1,2,3" 那么split(",") 将返回[1, 2, 3]

因此,要继续您的解决方案,您可以获得这样的发布日期:

new_string[0].strip

.strip 删除字符串前面或后面的空格,因此您将只剩下"Posted today"

【讨论】:

  • 您忘记了示例中 split 的参数。此外,用数组覆盖一个字符串变量通常不是一个好主意。你可以使用string.split(" More info").first
  • @EricDuminil 很好,我添加了参数。
【解决方案2】:

使用 Ruby sub,它将为您提供第一次出现的模式替换第二个参数的副本。

所以它将获取您的整个字符串"Posted 03-20-2017 More info Go to Last Post",将找到您的模式以及More info... 之后的所有内容,并将其替换为第二个参数More info,在这种情况下与第一个参数相同(你可以在那里使用一个变量)。

"Posted 03-20-2017 More info Go to Last Post".sub /More info.*/, 'More info'
=> "Posted 03-20-2017 More info"

gsub 也以类似的方式工作。

【讨论】:

  • /#{"More info"}.+/ == /More info.+/
  • /More info.+/ == /More info.*/ (?)
  • 不工作!不知何故,它给了我相同的输出“昨天发布\n\n更多信息\n\n转到最后一篇文章”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多