2014-10-03 62 views
0

我想查找一些模式后的字符串。我的代码似乎工作,但我无法完成这项工作。R使用正则表达式,与多种模式

这里有一个例子:

pattern <- c("Iligan", "Cabeseria 25|Sta. Lucia", "Capitol", "Osmeña", 
"Nowhere", "Aglayan") 

# I want to match the string just after each pattern. For example I'm going to 
# match City just after Iligan. 

    target <-c("Iligan City", "Sta. Lucia, Ozamiz City", " Oroquieta City", 
      "Osmeña St. Dipolog City", "Lucia St., Zamboanga City", 
"Aglayan str, Oroquieta City", "Gingoog City", "Capitol br., Ozamiz City", 
"Dumaguete City", "Poblacion, Misamis") 

#The matches seems to work fine 
(matches <- sapply(pattern,FUN=function(x){regexpr(paste0(" 
(?<=\\b",x,"\\b ",")","[\\w-*\\.]*"),target,perl=T)})) 
print (matches) 

#But I cannot get the results. I would need use the column of each matrix 
#at a time 
villain <- lapply(matches,FUN = function(x)(regmatches(target,x))) 

你有没有解决这个问题。

unpdate 1

对于被精确这里起见是所需的输出。

results <- c("City", "St.", "br.") 

#[1] "City" "St." "br." 
+1

预期产量是多少?只是匹配的字符串列表(没有'NA's)? – hrbrmstr 2014-10-03 11:11:41

+0

什么是unpdate? – amonk 2017-07-19 12:20:37

回答

3

里有stringr包中的一些助手,可以简化流程:

pattern <- c("Iligan", "Cabeseria 25|Sta. Lucia", "Capitol", "Osmeña", 
      "Nowhere", "Aglayan") 

target <-c("Iligan City", "Sta. Lucia, Ozamiz City", " Oroquieta City", 
      "Osmeña St. Dipolog City", "Lucia St., Zamboanga City", 
      "Aglayan str, Oroquieta City", "Gingoog City", "Capitol br., Ozamiz City", 
      "Dumaguete City", "Poblacion, Misamis") 


matchPat <- function(x) { 
    unlist(str_extract(target, perl(paste0("(?<=\\b", x, "\\b ",")","[\\w-*\\.]*")))) 
} 

matches <- sapply(pattern, matchPat) 

print(matches) 

##  Iligan Cabeseria 25|Sta. Lucia Capitol Osmeña Nowhere Aglayan 
## [1,] "City" NA      NA  NA  NA  NA  
## [2,] NA  NA      NA  NA  NA  NA  
## [3,] NA  NA      NA  NA  NA  NA  
## [4,] NA  NA      NA  "St." NA  NA  
## [5,] NA  NA      NA  NA  NA  NA  
## [6,] NA  NA      NA  NA  NA  "str" 
## [7,] NA  NA      NA  NA  NA  NA  
## [8,] NA  NA      "br." NA  NA  NA  
## [9,] NA  NA      NA  NA  NA  NA  
## [10,] NA  NA      NA  NA  NA  NA  

这可以进一步简化,如果你不需要非匹配指标,但没有样品/预期输出提供。