【问题标题】:Ruby Regex Rubular vs realityRuby Regex Rubular 与现实
【发布时间】:2014-06-30 22:20:30
【问题描述】:

我有一个字符串,我想从中删除所有非单词字符和空格。所以我认为正则表达式就是我所需要的。

我的 Regex 看起来像这样(我在字符串类中将它定义为方法):

/[\w&&\S]+/.match(self.downcase)

当我在 Rubular 中使用测试字符串 "hello ..a.sdf asdf..," 运行此表达式时,它会突出显示我需要的所有内容(“hellloasdfasdf”),但是当我在 irb 中执行相同操作时,我只会得到“hello”。

有人知道为什么会这样吗?

【问题讨论】:

    标签: ruby regex rubular


    【解决方案1】:

    \w 表示 [a-zA-Z0-9_]

    \S 表示任何非空白字符[a-zA-Z_-0-9!@#$%^&*\(\)\\{}?><....etc]

    所以使用\w and \S 条件是不明确的。

    就像说What is an intersection of India and Asia。显然,它将是印度。所以我建议你使用\w+

    您可以使用 scan 来获取第二个答案中提到的所有匹配项:

    string = "hello ..a.sdf asdf..,"
    string.scan(/\w+/)
    

    【讨论】:

      【解决方案2】:

      因为您使用match,所以返回一个匹配元素。如果你改用scan,一切都应该正常工作:

      string = "hello ..a.sdf asdf..,"
      string.downcase.scan(/[\w&&\S]+/)
      # => ["hello", "a", "sdf", "asdf"]
      

      【讨论】:

      • 感谢您的回答。是否有内置函数可以将该数组转换为一个字符串?
      • 好吧,我自己发现了。供参考:使用join方法。
      猜你喜欢
      • 2012-09-27
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2013-10-01
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多