【问题标题】:Ruby: extract substring between 2nd and 3rd fullstops [closed]Ruby:在第二个和第三个句号之间提取子字符串[关闭]
【发布时间】:2016-01-21 07:27:15
【问题描述】:

我正在用 Ruby 构建一个程序,该程序需要在字符串的第二个和第三个句号之间提取值。

我在网上搜索了各种相关解决方案,包括截断和之前的 Stack-Overflow 问题:Get value between 2nd and 3rd comma,但是没有答案说明 Ruby 语言的解决方案。

提前致谢。

【问题讨论】:

  • 怎么样,发布一个显示问题并尝试解决它的文件?
  • 这个问题似乎需要我们为你编写代码,或者推荐一个你可以从中复制代码的网站或书籍。这两个在 SO 上都是题外话。

标签: ruby string truncate


【解决方案1】:
list = my_string.split(".")
list[2]

我想这样就可以了。第一个命令将其拆分为一个列表。第二个得到你想要的位

【讨论】:

    【解决方案2】:

    您可以在full stops(又名句点)上拆分字符串,但这会创建一个数组,其中每个子字符串在句号之前都有一个元素。例如,如果文档有 100 万个这样的子字符串,那么仅获取第三个子字符串将是一种相当低效的方法。

    假设字符串是:

    mystring =<<_
    Now is the time
    for all Rubiests
    to come to the
    aid of their
    bowling team.
    Or their frisbee
    team. Or their
    air guitar team.
    Or maybe something
    else...
    _
    

    您可以采取以下几种方法。

    #1 使用正则表达式

    r = /
        (?:      # start a non-capture group
          .*?\.  # match any character any number of times, lazily, followed by a full stop
        ){2}     # end non-capture group and perform operation twice
        \K       # forget everything matched before
        [^.]*    # match everything up to the next full stop
        /xm      # extended/free-spacing regex definition mode and multiline mode
    
    mystring[r]
      #=> " Or their\nair guitar team"
    

    你当然可以写正则表达式:

    r = /(?:.*?\.){2}\K[^.]*/m
    

    但扩展的形式使其能够自我记录。

    正则表达式引擎将逐步遍历字符串,直到找到匹配项或断定不存在匹配项,然后停止。

    #2 假装句号是换行符

    首先假设我们正在寻找第三行,而不是第三个子字符串后跟一个句号。我们可以这样写:

    mystring.each_line.take(3).last.chomp
      # => "to come to the"
    

    Enumerable#take 通过检查由global variable $/ 保存的输入记录分隔符 来确定一行何时结束。默认情况下,$/ 等于换行符。因此我们可以这样做:

    irs = $/  # save old value, normally \n
    $/ = '.'
    mystring.each_line.take(3).last[0..-2]
      #=> " Or their\nair guitar team"
    

    那就不要留下脚印:

    $/ = irs
    

    这里String#each_line 返回一个枚举器(实际上是一个确定值序列的规则),而不是一个数组。

    【讨论】:

    • OP 的分隔符是句号,而不是换行符。
    • 顺便说一句,什么是 F1 比赛之外的“句号”?
    • 谢谢@Stefan。它是固定的。我认为。 ¯\_(ツ)_/¯
    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 2021-04-09
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多