【问题标题】:find json in string with R用R在字符串中查找json
【发布时间】:2020-04-05 08:00:05
【问题描述】:

给定一个字符串,我想在该字符串中提取 json。

非常类似于这个问题:Find JSON strings in a string 细绳。只为 R。

基本上,如果需要,我需要使用正则表达式和转义字符。因此,我调查了:Is there an R function to escape a string for regex characters

我尝试了什么:

txt <- "asdd {a:b, c:d} asdasd"
library(stringr)
quotemeta <- function(string) {
  str_replace_all(string, "(\\W)", "\\\\\\1")
}

quotemeta("\{(?:[^{}]|(?R))*\}")
str_extract_all(string = txt, pattern = quotemeta("\\{(?:[^{}]|(?R))*\\}"))
str_extract_all(string = txt, pattern = "\\{\\(\\?\\:\\[\\^\\{\\}\\]\\|\\(\\?R\\)\\)\\*\\}")
str_extract_all(string = txt, pattern = "\\\\{\\(\\?\\:\\[\\^\\{\\}\\]\\|\\(\\?R\\)\\)\\*\\\\}")

【问题讨论】:

  • ICU 正则表达式引擎不支持递归。将 regmatches / gregexpr 与 PCRE 正则表达式引擎一起使用。

标签: r json regex


【解决方案1】:

我使用regexpr()regmatches()

  • regexpr(pattern,text) :取与模式匹配的文本位置。
  • regmatches(m,x) :提取匹配的文本。
  • pattern :将\{ \} 变成\\{ \\}
regexpr("\\{(?:[^{}]|(?R))*\\}",txt,perl = T) %>% regmatches(x=txt)
#[1] "{a:b, c:d}"

这种模式可能更容易理解。

  • 这个模式是\\{(\\S|\\s)+\\}
    • \\{ 表示大括号“{”
    • (\\S|\\s)+ 表示大括号之间的所有空白字符和非空白字符。
    • \\} 表示大括号“}”
regexpr("\\{(\\S|\\s)+\\}",txt,perl = T) %>% regmatches(x=txt)
#[1] "{a:b, c:d}"

希望对你有用:)

【讨论】:

  • 很好的答案,欢迎来到#SO!可能,更多的是给我自己的便条,而不是在规范中询问,.....(但也许其他人需要它:如果有多个 json 只需使用 gregexpr() 而不是 regexpr()
  • 很高兴看到您的反馈。非常感谢=)
猜你喜欢
  • 2014-03-26
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多