Mark K
Mark K

Reputation: 9378

R, regex to find string matched

Wanted to find out if the elements are strictly of pattern “BQQ” followed by 3 digits.

pattern <- "^BQQ\\d{3}"
sum(table(grep(pattern, c("BQQ63252", "BQQ0508", "BQQ558", "BQQ202"), value = TRUE)))


[1] 4

It returns all 4 elements are matched. Seems it takes all the ones with 3 digits and more than 3 digits.

How can it consider only “BQQ” followed by 3 digits? Thank you.

Upvotes: 0

Views: 44

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522646

Add a closing anchor to your grep pattern:

pattern <- "^BQQ\\d{3}$"
grep(pattern, c("BQQ63252", "BQQ0508", "BQQ558", "BQQ202"))

[1] 3 4

Demo

Upvotes: 2

Related Questions