Regex 使用正则表达式函数时出错

Regex 使用正则表达式函数时出错,regex,r,Regex,R,我有一个文本对象,我只想提取以大写字母开头的连续单词(例如,John Rye)。我尝试使用regmatches()和gregexpr(),但出现错误。如何解决此问题 txt<-"This is John Rye walking." regmatches(txt, gregexpr('(.*)\s(.*)', txt, perl=T))[[1]] Error: '\s' is an unrecognized escape in character string starting "'(.*

我有一个文本对象,我只想提取以大写字母开头的连续单词(例如,John Rye)。我尝试使用regmatches()和gregexpr(),但出现错误。如何解决此问题

txt<-"This is John Rye walking."

regmatches(txt, gregexpr('(.*)\s(.*)', txt, perl=T))[[1]]
Error: '\s' is an unrecognized escape in character string starting "'(.*)\s"
但是得到了这个结果:

character(0)

^
$
是字符串锚的开头/结尾,您可能会将它们与单词边界混淆(
\b
\\b
如果转义)<代码>-看起来根本不合适

因此,正则表达式应该改为

\\b[A-Z][a-zA-Z]+\\b 

这也可以完成工作:

 txt<-"This is John Rye walking."
 regmatches(txt, gregexpr('(([A-Z])\\w+\\b ){2}', txt))[[1]]
 [1] "John Rye "

txt重点是需要使用
\\s
将反斜杠加倍。请尝试
regmatches(txt,gregexpr('\\b[A-Z][A-zA-Z]*',txt))[[1]
谢谢。如何确保只获取两个大写字母锁定的单词,如:“Jhon Rye”?请注意,您不需要最后的
\\b
,并且结尾的
+
不允许提取1个字母的单词。也许是后者ok@Wiktor最后省略
\b
将导致接受类似于
John123
的内容。不确定OP是否想要这些。@mql
(\\b[A-Z][A-zA-Z]+\\b?{2}
应该对您有帮助。@mql
,您忘记了括号。仔细看看我的评论。
 txt<-"This is John Rye walking."
 regmatches(txt, gregexpr('(([A-Z])\\w+\\b ){2}', txt))[[1]]
 [1] "John Rye "