Ruby 扫描以匹配多个单词

标签 ruby regex

<分区>

我有一段代码可以解析文件夹中的文本文件,并在特定搜索词周围保存文本。

但是,我在编辑代码以使其同时适用于多个单词时遇到了问题。我不想循环整个代码,因为我希望结果针对每个文本文件进行分组,而不是针对每个搜索词进行分组。

使用 all_documents.scan("(word1|word2|word3)") 或类似的正则表达式变体似乎不起作用。

    #helper
        def indices text, index, word
        padding = 20
        bottom_i = index - padding < 0 ? 0 : index - padding
        top_i = index + word.length + padding > text.length ? text.length : index +         word.length + padding
        return bottom_i, top_i
    end

    #script
    base_text = File.open("base.txt", 'w')
    Dir::mkdir("summaries") unless File.exists?("summaries")
    Dir.chdir("summaries")

    Dir.glob("*.txt").each do |textfile|
        whole_file = File.open(textfile, 'r').read
        puts "Currently summarizing " + textfile + "..."
        curr_i = 0
        str = nil
        whole_file.scan(/trail/).each do |match|
          if i_match = whole_file.index(match, curr_i)
            top_bottom = indices(whole_file, i_match, match)
            base_text.puts(whole_file[top_bottom[0]..top_bottom[1]] + " : " +         File.path(textfile))
            curr_i += i_match                     
          end
        end
        puts "Done summarizing " + textfile + "."
    end
    base_text.close

有什么想法吗?

最佳答案

您可以使用 Regexp.union()为了那个原因。它完全符合您的要求。

在你的代码中,它将变成

...
whole_file.scan(Regexp.union(/trail/, /word1/, /word2/, /word3/)).each do |match|
...

关于Ruby 扫描以匹配多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15421452/

相关文章:

ruby - 如何强制 Rack :session + sinatra to read "rack.session" from params instead of cookies

regex - 查找命令与 'regex' 匹配不工作

python 正则表达式。带有 unicode 字符

regex - 如何在jmeter中的正则extracor表达式中获得最后一场比赛?

正则表达式:分别捕获名称和部门

python - 尝试从字符串列中提取点之间的字符串值

ruby-on-rails - 在 Rails 中测试 Controller 助手重定向

ruby - 可能效率低下的算法

python - 通过 XML-RPC 使用 Python 访问 Ruby 对象?

ruby-on-rails - Google 日历与初始 time_max 增量同步