下面是我的正则表达式:https://regex101.com/r/UjWanf/1
(^\d+?\.?\d{0,2})([A-Za-z]+|\s[A-Za-z]+)转义为R:
"(^\\d+?\\.?\\d{0,2})([A-Za-z]+|\\s[A-Za-z]+)"在regex101中一切似乎都运行得很好,但是当我在R中使用strapplyc函数应用相同的模式时,它不能捕获整个字符串。
示例字符串:
50ml tomato sauce
5g chillies
5 Units tartar sauce
0.25 Units pasta sauce我想分别买50毫升、5克、5单位和0.25单位。
在R中,当我使用库gsubfn中的strapplyc应用上面的正则表达式链接中的模式时,我的输出是50m,5g,5U,0.25U。下面是我的代码示例: a=c("ingredient1",ingredient2","ingredient3","ingredient4") b=c("50ml番茄酱“,"5g辣椒”,“5Units tartar酱”,“0.25Units意大利面酱”) consolidated <- data.frame(a,b)`
library(gsubfn)
pattern_reg2 <- "(^\\d+?\\.?\\d{0,2})(\\s?[A-Za-z]+)"
consolidated$c <- strapplyc(consolidated$b, pattern_reg2)
#c column with the desired results有什么建议吗?
发布于 2018-02-15 08:55:05
我不熟悉strapplyc,但看起来它不能正常工作。您是否尝试过使用R的基本正则表达式函数?
library(RCurl)
#Load this webpage into a string so I can match the patterns you listed
test_file <- getURL("https://stackoverflow.com/questions/48798279/regex-working-in-regex101-not-in-r")
rgx = "(\\d+?\\.?\\d{0,2})([A-Za-z]+|\\s[A-Za-z]+)" #removed the ^ to allow whole string matching
rgx_result <- gregexpr(rgx,test_file)
result <- regmatches(test_file, rgx_result)
result[[1]][317:321] #only the answers from the strings you were asking to match返回:
[1] "50ml" "5g" "5 Units" "25 Units" "50ml" 这是正常工作的。有什么理由需要使用strapplyc吗?
添加了在列表中工作的示例:
test_list <- list('50ml tomato sauce','5g chillies',
'5 Units tartar sauce',
'0.25 Units pasta sauce')
for(i in 1:length(test_list)) {
rgx_result <- gregexpr(rgx,test_list[[i]])
print(regmatches(test_list[[i]], rgx_result))
}我确信使用apply函数可以更干净地完成这项工作,但我不太擅长使用这些函数。
https://stackoverflow.com/questions/48798279
复制相似问题