regex之R中正则表达式的异常处理

myhome 阅读:38 2025-02-15 21:57:57 评论:0

我发现了几个相关的问题,但还没有找到一个可以解决我的问题,如果我遗漏了一个可以解决这个问题的问题,请告诉我。

本质上,我想使用正则表达式来查找模式,但有一个基于前面字符的异常。例如,我将以下文本对象(“muffins”)作为向量,我想匹配名称(“Sarah”、“Muffins”和“Bob”)。:

muffins 

[1] "Dear Sarah,"
[2] "I love your dog, Muffins, who is adorable and very friendly. However, I cannot say I enjoy the \"muffins\" he regularly leaves in my front yard. Please consider putting him on a leash outside and properly walking him like everyone else in the neighborhood."

[3] "Sincerely,"
[4] "Bob"

我的方法是搜索大写单词,然后出于语法原因排除大写单词,例如句子的开头。

 pattern = "\\b[[:upper:]]\\w+\\b" 
 m = gregexpr(pattern,muffins) 
 regmatches(muffins,m) 

这个模式让我大部分时间返回:

[[1]] [1] "Dear" "Sarah"

[[2]] [1] "Muffins" "However" "Please"

[[3]] [1] "Sincerely"

[[4]] [1] "Win"

我可以识别出一些以以下开头的句子:

 pattern2 = "[.]\\s[[:upper:]]\\w+\\b" 
 m = gregexpr(pattern2,muffins) 
 regmatches(muffins,m) 

但我似乎不能同时做这两件事,我说我想要 pattern 而 pattern2 不是这种情况。

我尝试了几种我认为可行的组合,但收效甚微。我试过的一些:

pattern2 = "(?<![.]\\s[[:upper:]]\\w+\\b)(\\b[[:upper:]]\\w+\\b)" 
pattern2 = "(^[.]\\s[[:upper:]]\\w+\\b)(\\b[[:upper:]]\\w+\\b)" 

任何建议或见解将不胜感激!

请您参考如下方法:

您可能正在寻找消极的回顾。

pattern = "(?<!\\.\\s)\\b[[:upper:]]\\w+\\b" 
m = gregexpr(pattern,muffins, perl=TRUE) 
regmatches(muffins,m) 
 
# [[1]] 
# [1] "Dear"  "Sarah" 
#  
# [[2]] 
# [1] "Muffins" 
#  
# [[3]] 
# [1] "Sincerely" 
#  
# [[4]] 
# [1] "Bob" 

后面的部分(?<!\\.\\s)确保在匹配之前没有句点和空格。


声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号