【问题标题】:Ruby Is a string present within another string (using a regexp)?Ruby 一个字符串是否存在于另一个字符串中(使用正则表达式)?
【发布时间】:2012-02-17 06:18:16
【问题描述】:

ruby 中是否有 present? 方法来检查字符串是否存在于另一个字符串中?我想在找到匹配项后立即返回,因为我将检查多个子字符串。谢谢!

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

我相信你的意思是include?

【讨论】:

    【解决方案2】:

    我相信您正在寻找包含?

    "ab123de".include?("123")
    

    【讨论】:

      【解决方案3】:
      【解决方案4】:

      抱歉,找到了我要找的东西(因为使用了 regexp):

      index(regexp [, offset]) → fixnum 或 nil

      返回索引 str 中给定子字符串或模式 (regexp) 的第一次出现。 如果没有找到则返回 nil。

      "hello".index('lo')            #=> 3
      "hello".index('a')             #=> nil
      "hello".index(?e)              #=> 1
      "hello".index(/[aeiou]/, -3)   #=> 4
      

      http://ruby-doc.org/core-1.9.3/String.html

      我只是使用循环检查索引是否为零

      【讨论】:

      • 仅供参考,还有更多类似 Ruby 的方法:'hello'['lo']'hello'[/lo/]
      • 很高兴知道,谢谢!我认为在这种情况下,我仍然会花费额外的 5 个字符,以确保每个人都清楚发生了什么。编辑:只是为了澄清其他人 'hellohello'['lo'] => lo,而不是索引,但仍然可以工作,因为 'hell'['lo'] => nil
      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2014-02-08
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      相关资源
      最近更新 更多