如何使用 R 中的正则表达式从字符串中提取所有三(五)位数字?

How to extract all three (five) digits from the string using regular expressions in R?

我是正则表达式的新手,所以我向你寻求帮助。

我有一个字符串值,比方说,102-105+106-10605-10605 -10610-10610+10613。如何轻松提取三位数的所有值,五位数的所有值。另一个任务是考虑值之前的 + or - 符号。比如说,提取前面有符号 - 的所有 5 位数字的值。

我知道 R 中有一些包可以让您做到这一点。但我不知道该怎么做。我尝试了各种代码,但不幸的是我每次都失败了。

更新:

我想从我提到的 yhe 向量中提取所有三位数和五位数的值。

我用了代码

str_extract_all(d, ("\d{3}"))

它给了我

[1] "102" "105" "106" "106" "106" "106" "106" "106" "106" "106". 

但是我想要下面的结果"102" "105" "106"。即代码不应考虑 acconts 5 位数的值并从中连续提取任何三位数。

如果是 5 位数查询 str_extract_all(d, ("\d{5}")) 它会给我

[1] "10605" "10605" "10610" "10610" "10613" "10613" "10620". 

这个结果是真的。

希望我解释得当。

vect <- "102-105+106-10605-10605 -10610-10610+10613"

#Extract 3 digits
str_extract_all(vect, pattern = "[:digit:]{3}")
[[1]]
[1] "102" "105" "106" "106" "106" "106" "106" "106"

#Extract 5 digits    
str_extract_all(vect, pattern = "[:digit:]{5}")
[[1]]
[1] "10605" "10605" "10610" "10610" "10613"

#Extract 5 digits with minus sign ahead of it
str_extract_all(vect, pattern = "-[:digit:]{5}")
[[1]]
[1] "-10605" "-10605" "-10610" "-10610"

希望对您有所帮助
以供参考: https://stringr.tidyverse.org/articles/regular-expressions.html

编辑:根据您的评论

vect2 <- str_split(vect, pattern = "[^[:alnum:]]")
vect2
[[1]]
[1] "102"   "105"   "106"   "10605" "10605" ""      "10610" "10610" "10613"

unlist(str_extract_all(unlist(vect2), pattern = "^[:digit:]{3}$"))
[1] "102" "105" "106"

你可以这样做...

library(stringr)
d<-"102-105+106-10605-10605 -10610-10610+10613"

str_match_all(d, "\b([\+\-]*\d{3})\b")[[1]][,2]
[1] "102"  "-105" "+106"

str_match_all(d, "\b([\+\-]*\d{5})\b")[[1]][,2]
[1] "-10605" "-10605" "10610"  "-10610" "+10613"

如果您不想捕获前导 +/-,请删除 [\+\-]*

\b 是 "word boundary" 的正则表达式 - 单词(或在本例中为数字)的开头或结尾。