【问题标题】:Regex to match a specific sequence of strings正则表达式匹配特定的字符串序列
【发布时间】:2016-09-08 13:07:47
【问题描述】:

假设我有 2 个字符串数组 位置1 = ['word1','word2','word3'] position2 = ['word4', 'word1']

并且我想在文本/字符串中检查文本中存在的子字符串#{target} 后面是 position1 的单词之一还是 position1 的单词之一em>position2 甚至两者同时进行。同样,好像我在看#{target}的左右。

例如,如果目标词是data,则在句子“Writing reports and inputing data into internal systems, 有关执法和移民文件”中,我想检查单词left(输入)和right(onto)是否包含在数组中,或者数组中的单词之一是否为正则表达式匹配返回true。有什么建议么?我正在使用 Ruby,我尝试了一些正则表达式,但我还不能让它工作。我还必须忽略介于两者之间的任何潜在特殊字符。

其中一个:

/^.*\b(#{joined_position1})\b.*$[\s,.:-_]*\b#{target}\b[\s,.:-_\\\/]*^.*\b(#{joined_position2})\b.*$/i

编辑:

我想出了用正则表达式来捕获左右单词的方法:

(\S+)\s*#{target}\s*(\S+)

但是,如果我想左右捕捉多个单词,我可以改变什么?

【问题讨论】:

    标签: ruby regex string


    【解决方案1】:

    如果你有两个字符串数组,你可以这样做:

    matches = /^.+ (\S+) #{target} (\S+) .+$/.match(text)
    if matches and (position1.include?(matches[1]) or position2.include?(matches[2]))
        do_something()
    end
    

    这个正则表达式的作用是匹配文本中的目标词,并使用捕获组提取它旁边的词。然后代码将这些单词与您的数组进行比较,如果它们位于正确的位置,则执行某些操作。更通用的版本可能如下所示:

    def checkWords(target, text, leftArray, rightArray, numLeft = 1, numRight = 1)
        # Build the regex
        regex = "^.+"
        regex += " (\S+)" * numLeft
        regex += " #{target}"
        regex += " (\S+)" * numRight
        regex += " .+$"
    
        pattern = Regexp.new(regex)
        matches = pattern.match(text)
    
        return false if !matches
    
        for i in 1..numLeft
            return false if (!leftArray.include?(matches[i]))
        end
    
        for i in 1..numRight
            return false if (!rightArray.include?(matches[numLeft + i]))
        end
    
        return true
    end
    

    然后可以这样调用:

    do_something() if checkWords("data", text, position1, position2, 2, 2)
    

    我很确定这不是非常地道,但它可以让您大致了解如何以更一般的方式做事。

    【讨论】:

    • 感谢您的回复。我不明白为什么它会抛出 NoMethodError: undefined method `[]' for nil:NilClass for matches 虽然匹配应该存在于文本中
    • 我更新了它,如果没有找到您的目标文本,它不会崩溃。
    • 谢谢。是否可以使用正则表达式包含 2 个或更多相邻单词而不是一个?
    • 无论如何我可以重复 (.+) 但我想知道是否有更有效的方法
    • @Vas:我添加了一个更通用的版本,可以满足您的需求。
    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 2014-10-08
    • 2018-01-09
    相关资源
    最近更新 更多