首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式在Regex101中工作,而不是在R中

正则表达式在Regex101中工作,而不是在R中
EN

Stack Overflow用户
提问于 2018-02-15 08:11:28
回答 1查看 527关注 0票数 0

下面是我的正则表达式:https://regex101.com/r/UjWanf/1

代码语言:javascript
复制
(^\d+?\.?\d{0,2})([A-Za-z]+|\s[A-Za-z]+)

转义为R:

代码语言:javascript
复制
"(^\\d+?\\.?\\d{0,2})([A-Za-z]+|\\s[A-Za-z]+)"

在regex101中一切似乎都运行得很好,但是当我在R中使用strapplyc函数应用相同的模式时,它不能捕获整个字符串。

示例字符串:

代码语言:javascript
复制
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)`

代码语言:javascript
复制
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

有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2018-02-15 08:55:05

我不熟悉strapplyc,但看起来它不能正常工作。您是否尝试过使用R的基本正则表达式函数?

代码语言:javascript
复制
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

返回:

代码语言:javascript
复制
[1] "50ml"     "5g"       "5 Units"  "25 Units" "50ml"   

这是正常工作的。有什么理由需要使用strapplyc吗?

添加了在列表中工作的示例:

代码语言:javascript
复制
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函数可以更干净地完成这项工作,但我不太擅长使用这些函数。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48798279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档