从R中的字符向量中提取电子邮件地址(具有已知域)

时间:2015-12-13 23:00:21

标签: regex r

我有一个字符向量(myVector),其中包含多个电子邮件地址实例,这些实例分散在存储在向量中单个条目中的一长串半清理HTML中。

我知道相关的域名(" @ domain.com"),我想提取与该域名相关的每个电子邮件地址(例如" help@domain.com")之前是空格。

我尝试过以下代码,但它没有提供正确的子字符串索引:

gregexpr("\\s .+?@domain.com", myVector)

关于(a)如何修复正则表达式以及(b)是否有更优雅的解决方案的任何想法?

3 个答案:

答案 0 :(得分:1)

我尝试通过创建一个包含少量电子邮件的单个字符串来复制您的问题。

> foo = "thing1@gmail.com some filler text to use an thing2@gmail.com example for this 
thing3@gmail.com question thing4@gmail.com that OP has has asked"

> strsplit(foo, " ")
[[1]]
 [1] "thing1@gmail.com"       "some"                   "filler"                
 [4] "text"                   "to"                     "use"                   
 [7] "an"                     "thing2@gmail.com"       "example"               
[10] "for"                    "this\nthing3@gmail.com" "question"              
[13] "thing4@gmail.com"       "that"                   "OP"                    
[16] "has"                    "has"                    "asked"

> strsplit(foo, " ")[[1]][grep("@gmail.com", strsplit(foo, " ")[[1]])]

[1] "thing1@gmail.com"       "thing2@gmail.com"       "this\nthing3@gmail.com"
[4] "thing4@gmail.com" 

答案 1 :(得分:1)

使用grepvalue = TRUE

str1 <-"Long text with email addresses help@domain.com and info@domain.com throughout help@other.com"
str1 <-unlist(strsplit(str1, " ")) #split on spaces
grep("@domain.com", str1, value = TRUE)
#[1] "help@domain.com" "info@domain.com"

答案 2 :(得分:1)

你想要空格后跟无空格,所以gregexpr("\\s\\S+@domain.com", myVector)应该没问题(但是它会在开始时计算额外的空间)。

作为替代解决方案,请查看stringr包:

library(stringr)
str_extract_all(myVector, "\\s\\S+@domain.com")

或者使用str_extract_all(myVector, "\\S+@domain.com"),它还会在字符串的开头处返回(并且没有额外的空格)。

示例:

myVector <- "one@domain.com and two@domain.com and three@domain.com. What about:four@domain.com and five@domain.com"
gregexpr("\\s\\S+@domain.com", myVector)
# [[1]]
# [1] 19 38 61 87
# attr(,"match.length")
# [1] 15 17 22 16
# attr(,"useBytes")
# [1] TRUE

str_extract_all(myVector, "\\s\\S+@domain.com")
# [1] " two@domain.com"        " three@domain.com"      " about:four@domain.com"
# [4] " five@domain.com"   

str_extract_all(myVector, "\\S+@domain.com")
# [1] "one@domain.com"        "two@domain.com"        "three@domain.com"     
# [4] "about:four@domain.com" "five@domain.com"      

about:four是一个值得思考的角落)