【问题标题】:Extract text between certain symbols using Regular Expression in R使用 R 中的正则表达式提取某些符号之间的文本
【发布时间】:2014-11-07 20:50:35
【问题描述】:

我有一系列的表达方式如:

"<i>the text I need to extract</i></b></a></div>"

我需要提取&lt;i&gt;&lt;/i&gt;“符号”之间的文本。也就是说,结果应该是:

"the text I need to extract"

目前我在 R 中使用 gsub 手动删除所有非文本符号。但是,我想使用正则表达式来完成这项工作。有谁知道提取&lt;i&gt;&lt;/i&gt; 之间的正则表达式吗?

谢谢。

【问题讨论】:

    标签: regex r


    【解决方案1】:

    如果只有一个 &lt;i&gt;...&lt;/i&gt; (如示例中所示),则匹配直到 &lt;i&gt; 的所有内容以及来自 &lt;/i&gt; 的所有内容,并将它们都替换为空字符串:

    x <- "<i>the text I need to extract</i></b></a></div>"
    gsub(".*<i>|</i>.*", "", x)
    

    给予:

    [1] "the text I need to extract"
    

    如果同一字符串中可能出现多次,请尝试:

    library(gsubfn)
    strapplyc(x, "<i>(.*?)</i>", simplify = c)
    

    在此示例中给出相同的内容。

    【讨论】:

      【解决方案2】:

      这种方法使用我维护的一个包qdapRegex,它不是正则表达式,但可能对您或未来的搜索者有用。函数rm_between 允许用户在左右边界之间提取文本,并可选择包含它们。这种方法很简单,因为您不必考虑特定的正则表达式,只需考虑确切的左右边界:

      library(qdapRegex)
      
      x <- "<i>the text I need to extract</i></b></a></div>"
      
      rm_between(x, "<i>", "</i>", extract=TRUE)
      
      ## [[1]]
      ## [1] "the text I need to extract"
      

      我会指出,使用 html 解析器来完成这项工作可能更可靠。

      【讨论】:

      • +1 用于指出该文本应使用 html 解析器
      【解决方案3】:

      如果这是 html(看起来就是这样),您可能应该使用 html 解析器。包XML可以这样做

      library(XML)
      x <- "<i>the text I need to extract</i></b></a></div>"
      xmlValue(getNodeSet(htmlParse(x), "//i")[[1]])
      # [1] "the text I need to extract"
      

      在整个 html 文档上,你可以使用

      doc <- htmlParse(x)
      sapply(getNodeSet(doc, "//i"), xmlValue)
      

      【讨论】:

      【解决方案4】:

      如果您不知道字符串中的匹配数,您可以对gregexprregmatches 使用以下方法。

      vec <- c("<i>the text I need to extract</i></b></a></div>",
               "abc <i>another text</i> def <i>and another text</i> ghi")
      
      regmatches(vec, gregexpr("(?<=<i>).*?(?=</i>)", vec, perl = TRUE))
      # [[1]]
      # [1] "the text I need to extract"
      # 
      # [[2]]
      # [1] "another text"     "and another text"
      

      【讨论】:

        【解决方案5】:
        <i>((?:(?!<\/i>).)*)<\/i>
        

        这应该为你做。

        【讨论】:

          猜你喜欢
          • 2017-03-11
          • 1970-01-01
          • 2019-02-06
          • 2011-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多