正则表达式匹配R中的处理

时间:2012-11-24 18:34:54

标签: regex r

我想用R提取2个匹配的组。 现在我已经有了这个,但效果不好:

代码:

str = '123abc'
vector <- gregexpr('(?<first>\\d+)(?<second>\\w+)', str, perl=TRUE)
regmatches(str, vector)

结果:

[[1]]
[1] "123abc"

我希望结果是这样的:

[1] "123"
[2] "abc"

4 个答案:

答案 0 :(得分:2)

我不确定您是否有使用regmatches的具体原因,除非您是以该格式导入表达式。如果明确定义的组对所有条目都是通用的,则可以通过以下方式匹配它们:

x <- "123abc"
sub("([[:digit:]]+)[[:alpha:]]+","\\1",x)
sub("[[:digit:]]+([[:alpha:]]+)","\\1",x)

结果

[1] "123"
[1] "abc"

即匹配字符串的整个结构,然后将其替换为要保留的部分,方法是将其括在圆括号中并用反向引用(“\\ 1”)引用它。

答案 1 :(得分:1)

我已重命名您的字符串s以避免遭遇str。这是一种方法:

library(stringr)
s <- '123abc'
reg <- '([[:digit:]]+)([[:alpha:]]+)'

complete <- unlist(str_extract_all(s, reg))
partials <- unlist(str_match_all(s, reg))
partials <- partials[!(partials %in% complete)]

partials
[1] "123" "abc"

答案 2 :(得分:0)

根据输入结构的完整程度,您可能希望使用strsplit来分割字符串。

文档here

答案 3 :(得分:0)

试试这个:

> library(gsubfn)
> strapplyc("123abc", '(\\d+)(\\w+)')[[1]]
[1] "123" "abc"
相关问题