【问题标题】:How to capture a few words before a certain word in Regexp如何在Regexp中的某个单词之前捕获几个单词
【发布时间】:2012-01-19 10:16:58
【问题描述】:

从字符串"Fabulous two, three, or six night Stay For Two With Meals" 我想捕捉单词'night'之前的5个单词。 在这个例子中我想得到['Fabulous', 'two', 'three', 'or', 'six']

我目前正在使用s.scan(/(?:\w+)/),它返回标记化数组:

["fabulous", "two", "three", "or", "six", "night", "Stay", "For", "Two", "With", "Meals"]

然后我通过索引找到“夜晚”这个词。但是我想知道正则表达式是否也可以完成这一步。

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    只需在您的扫描中添加一个积极的前瞻,以确保紧随其后的是“夜晚”一词:

    s.scan(/(?:\w+)(?=.*night)/)
    
    #=> ["Fabulous", "two", "three", "or", "six"]
    

    【讨论】:

      【解决方案2】:

      使用/(?:\w+\W+){5}(?=night)/可以得到前面5个词,返回"Fabulous two, three, or six "。然后您可以继续将其拆分为单词(无法弄清楚如何将它们放在同一个正则表达式中)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多