str_extract特定模式(示例)

时间:2014-12-03 14:18:24

标签: regex r

我仍然对正则表达式语法感到困惑。你能帮我解决这些模式:

_A00_A1234B_
_A00_A12345B_
_A1_A12345_

到目前为止我的方法:

vapply(strsplit(files, "[_.]"), function(files) files[nchar(files) == 7][1], character(1))

str_extract(str2, "[A-Z][0-9]{5}[A-Z]")

预期产出

A1234B
A12345B
A12345

谢谢!

4 个答案:

答案 0 :(得分:2)

你可以尝试

library(stringr)
str_extract(str2, "[A-Z][0-9]{4,5}[A-Z]?")
#[1] "A1234B"  "A12345B" "A12345" 

此处,模式会查找大写字母[A-Z],后跟4或5位[0-9]{4,5},后跟大写字母[A-Z] ? < / p>

或者你可以使用更快的stringi

library(stringi)
 stri_extract(str2, regex="[A-Z][0-9]{4,5}[A-Z]?")
 #[1] "A1234B"  "A12345B" "A12345" 

base R选项

 regmatches(str2,regexpr('[A-Z][0-9]{4,5}[A-Z]?', str2))
 #[1] "A1234B"  "A12345B" "A12345" 

数据

str2 <- c('_A00_A1234B_', '_A00_A12345B_', '_A1_A12345_')

答案 1 :(得分:2)

vec <- c("_A00_A1234B_", "_A00_A12345B_", "_A1_A12345_")

您可以使用sub和此正则表达式:

sub(".*([A-Z]\\d{4,5}[A-Z]?).*", "\\1", vec)
# [1] "A1234B"  "A12345B" "A12345" 

答案 2 :(得分:1)

使用rex构造正则表达式可能会使其更容易理解。

x <- c("_A00_A1234B_", "_A00_A12345B_", "_A1_A12345_")

# approach #1, assumes always is between the second underscores.
re_matches(x,
  rex(
    "_",
    anything,
    "_",
    capture(anything),
    "_"
  )
)

#>         1
#> 1  A1234B
#> 2 A12345B
#> 3  A12345


# approach #2, assumes an alpha, followed by 4 or 5 digits with a possible trailing alpha.
re_matches(x,
  rex(
    capture(
      alpha,
      between(digit, 4, 5),
      maybe(alpha)
    )
  )
)

#>         1
#> 1  A1234B
#> 2 A12345B
#> 3  A12345

答案 3 :(得分:1)

您可以在不使用正则表达式的情况下执行此操作...

x <- c('_A00_A1234B_', '_A00_A12345B_', '_A1_A12345_')
sapply(strsplit(x, '_', fixed=T), '[', 3)
# [1] "A1234B"  "A12345B" "A12345" 

如果您坚持使用正则表达式,以下就足够了。

regmatches(x, regexpr('[^_]+(?=_$)', x, perl=T))