R 将引号之间一个或多个大写单词的子字符串与正则表达式匹配

R 将引号之间一个或多个大写单词的子字符串与正则表达式匹配,r,regex,stringr,R,Regex,Stringr,我有以下字符串: example_string <- "In this document, Defined Terms are quotation marks, followed by definition. \"Third Party Software\" is software owned by third parties. \"USA\" the United States of America. \"Breach of C

我有以下字符串:

example_string <- "In this document, Defined Terms are quotation marks, followed by definition. \"Third Party Software\" is software owned by third parties. \"USA\" the United States of America. \"Breach of Contract\" is in accordance with the Services Description."
我用正则表达式得出了这样的结论:

str_extract_all(example_string, "(?:\")\\w(\\s*\\w+)*")

[[1]]
[1] "\"Third Party Software" "\"USA"                  "\"Breach of Contract"
我想不出一种方法来避免匹配开头转义引号
\“
。我知道我可以在提取定义的术语后添加一行
gsub
来清除它,但我认为一定有一种方法可以在一个regex调用中完成这一切

非常感谢您的建议!

在您的表达式中,
(?:”)\w(\s*\w+)*“
,您使用非捕获的
(?:”
组匹配并使用
字符。因此,它将进入匹配值

你可能想用

"(?<=\")\\w(\\s*\\w+)*"
或者,它也可以是您的模式,稍作修改:

"(\p{Lu}\w*(?:\s+\w+)*)"
请参阅,或。详细信息:

  • -a
    字符
  • (\p{Lu}[^”]*)
    -捕获组1:
    • \p{Lu}
      -任何Unicode大写字母
    • [^”]*
      -除
  • \w*(?:\s+\w+*
    -0+个字母、数字、下划线,然后0+次出现1+个空格,后跟1+个字母、数字、下划线
  • -一个
    字符
见:

库(stringr)

示例\u字符串打开
后的第一个字母必须是大写字母?你说的“至少部分大写”是什么意思?第一个字母总是大写的。我说“至少部分大写”,是因为有像“违约”这样的例子,其中一个单词没有大写,还有像“美国”这样的例子“整个单词都大写了,谢谢!我可以用我的正则表达式和
gsub(“\”,“,”,res[,2])
实现同样的效果,我的问题更多的是,为什么不包含引号就无法在开头的引号内捕获。@mendy您使用了它。您需要
”(?谢谢,这回答了我的问题。当分隔符相同时,为什么您更喜欢捕获方法?@mendy Comapre to。啊,我明白了,它避免了将引用块两侧的字符视为在引号内?
"(\p{Lu}[^"]*)"
"(\p{Lu}\w*(?:\s+\w+)*)"
library(stringr)
example_string <- "In this document, Defined Terms are quotation marks, followed by definition. \"Third Party Software\" is software owned by third parties. \"USA\" the United States of America. \"Breach of Contract\" is in accordance with the Services Description."
res <- str_match_all(example_string, '"(\\p{Lu}[^"]*)"')
unlist(lapply(res, function(x) x[,-1]))
## => [1] "Third Party Software" "USA"                  "Breach of Contract"