【问题标题】:Extract text next line ignoring whitespaces提取文本下一行忽略空格
【发布时间】:2015-12-12 15:22:53
【问题描述】:

Here,我问如何匹配一个字符串后的下一行。

有时,我的 PDF 包含一些扭曲我的结果的空格。例如,有时我有:

Title:  
this is the text I'd like to extract  
Not this one
Neither this  
(here my code works well)  

有时,它的格式如下:

Title:

this is the text I'd like to extract  
Not this one  
Neither this  

这是我在 Ruby 中的正则表达式:

^(?<=Title:\n)([^\n]+$)

如果我的匹配文本是 cacharecters [原文如此](文本或数字)而不是空格,我如何让正则表达式提取下一行?

【问题讨论】:

    标签: ruby regex parsing pdf


    【解决方案1】:

    如果你已经将整个文件读入字符串:

    text =
    "Title:
    
    this is the text I'd like to extract  
    Not this one  
    Neither this"
    

    你可以写:

    r = /
        \b          # Match a word break
        Title:\s*\n # Match string
        \n*         # Match >= 0 newlines
        \K          # Forget everything matched so far
        [^\n]+      # Match as many characters as possible other than new lines
        /x          # Extended/free-spacing regex definition mode
    
    text[r]
      #=> "this is the text I'd like to extract  " 
    

    另一种方式(在众多方式中)是:

    lines = text.split(/\n+/)
      #=> ["Title:", "this is the text I'd like to extract  ",
      #    "Not this one  ", "Neither this"] 
    lines[lines.index { |l| l.start_with?("Title:") } + 1]
      #=> "this is the text I'd like to extract  " 
    

    【讨论】:

      【解决方案2】:
      \S
      

      不是空格

      \s
      

      空格。

      ^(?<=Title:\n)([^\n\S]+$)
      

      可能并不完全正确,但您应该能够了解如何使用它的要点。本质上,您需要运行 if else 语句来确定在到达下一个字符之前需要循环多少额外的新行,具体取决于是否有匹配的空格。我添加到代码中的内容应该是这样的。

      Start at a newline(\n) that does not have a white space(\S) before the matched string($).
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-04
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-28
        • 1970-01-01
        相关资源
        最近更新 更多