Reputation: 45
In R I would like the code to find numbers starting with 4 or 6 in numbers with 10 digits.
This works to get the 10 digit numbers:
grep("^[[:digit:]]{10}$"
This doesn't work to get them starting with 4 or 6:
grep([46]\"^[[:digit:]]{10}$"
Examples
x <- c("4303669792", "6200406014")
Upvotes: 1
Views: 231
Reputation: 388982
We can use grepl
and nchar
grepl("^[4|6]", x) & nchar(x) == 10
#[1] TRUE TRUE FALSE FALSE
With grepl
find if string starts with "4" or "6" and check if number of characters in it is equal to 10.
If you need the values, subset it
x[grepl("^[4|6]", x) & nchar(x) == 10]
#[1] "4982748923" "6165751984"
data
x <- c('4982748923', '6165751984', '31094583285', '654')
Upvotes: 1
Reputation: 51592
You can use simple math as well, i.e.
x <- c('4982748923', '6165751984', '31094583285')
as.numeric(x) %/% 1000000000 %in% c(4, 6)
#[1] TRUE TRUE FALSE
Upvotes: 1
Reputation: 626861
You may use
grep("^[46][0-9]{9}$", x)
^^^^ ^
Details
^
- start of string[46]
- 4
or 6
[0-9]{9}
- nine digits$
- end of string.See the regex demo and a Regulex graph:
Upvotes: 3