R gsub返回的比正则表达式匹配的多

R gsub返回的比正则表达式匹配的多,r,regex,R,Regex,我有这样的弦 x = c( "blahblah, blah blah, Plate 3, blah blah" , "blah blah, blah_Plate 2_blah, blah" , "blah, blah, blah blah, blah plate_3" , "blah blah, blah, plate 5.txt" ) 我想从所有这些文件名中得到车牌号 所以我正在测试我的正则表达式与 gsub("\\<Plate\\>.[0-9]","\\1",workdf_n

我有这样的弦

x = c(
"blahblah, blah blah, Plate 3, blah blah"
,
"blah blah, blah_Plate 2_blah, blah"
,
"blah, blah, blah blah, blah plate_3"
,
"blah blah, blah, plate 5.txt"
)
我想从所有这些文件名中得到车牌号

所以我正在测试我的正则表达式与

 gsub("\\<Plate\\>.[0-9]","\\1",workdf_nums_plats$Bioplex_Files)
gsub(“\\.[0-9]”,“\\1”,workdf\u nums\u plats$Bioplex\u文件)
所以我最终可以这样做

workdf_nums_plats$plat <- ifelse(grepl("\\<Plate\\>.[0-9]", workdf_nums_plats$Bioplex_Files), gsub("\\<Plate\\>.[0-9]","\\1",workdf_nums_plats$Bioplex_Files), NA)

workdf\u nums\u plats$plat您需要在内部定义一个捕获组,并以不区分大小写的方式匹配
plate
,但不能作为一个完整的单词,因为您需要在
\u
之后匹配它(它也是一个单词字符):


这里,
(?i)
是一个不区分大小写的标志,
(?一种方法是使用
regmatches
regexec
返回捕获的子表达式

regmatches(test, regexec("[Pp]late.?([0-9]+)", test))
[[1]]
[1] "Plate 3" "3"      

[[2]]
[1] "Plate 2" "2"      

[[3]]
[1] "plate_3" "3"      

[[4]]
[1] "plate 5" "5" 
这里,[Pp]将匹配“p”或“p”,“late”按字面意思匹配,“.?”匹配任何字符的0或1,“()”捕获所需的值,即“[0-9]+”,一个或多个数字

由于这将返回一个列表,您需要使用
sapply
从每个列表项中提取第二个元素,如下所示

sapply(regmatches(test, regexec("[Pp]late.?([0-9]+)", test)), "[", 2)
[1] "3" "2" "3" "5"
数据

test <- 
c("blahblah, blah blah, Plate 3, blah blah", "blah blah, blah_Plate 2_blah, blah", 
"blah, blah, blah blah, blah plate_3", "blah blah, blah, plate 5.txt")

test感谢您帮助我了解我自己的解决方案并提供替代解决方案!@AwesomeeExpress只是想让我知道您也可以使用
str_匹配(Bioplex_文件,“(?i)(?:| \\b)板。([0-9]+)”[,2]很高兴帮助你。谢谢!你的解决方案比我的更优雅,ReX非常…深。看起来你发现这些答案很有帮助。考虑接受对你最有帮助的一个(在答案左边选中标记)。
regmatches(test, regexec("[Pp]late.?([0-9]+)", test))
[[1]]
[1] "Plate 3" "3"      

[[2]]
[1] "Plate 2" "2"      

[[3]]
[1] "plate_3" "3"      

[[4]]
[1] "plate 5" "5" 
sapply(regmatches(test, regexec("[Pp]late.?([0-9]+)", test)), "[", 2)
[1] "3" "2" "3" "5"
test <- 
c("blahblah, blah blah, Plate 3, blah blah", "blah blah, blah_Plate 2_blah, blah", 
"blah, blah, blah blah, blah plate_3", "blah blah, blah, plate 5.txt")