Home > front end >  Regex: matching for only one number in an integer R
Regex: matching for only one number in an integer R

Time:11-10

I have an example list of numbers:

888*
8*
8.88*
88.88*
88888.888*
899900
8.89
0.08
80
89899
50
32
30.8
0.081
0.8
8.1

and I only want to match those that have only 8's. I put an asterisk for the ones I only want and the others should be ignored.

I tried this but could only get partially what I wanted.

num <- c(888,
  8,
  8.88,
  88.88,
  88888.888,
  899900,
8.89,
0.08,
80,
89899,
50,
32,
30.8,
0.081,
0.8,
8.1)

grepl('^8 [^\\.]*[^0-7|9]*', num)

CodePudding user response:

How about:

grep("^[8.] $", num, value = TRUE)
# "888"       "8"         "8.88"      "88.88"     "88888.888"

CodePudding user response:

Assuming that L is as in the Note at the end try any of these. They all also work if L is numeric.

# there cannot be anything other than 8 and dot 
!grepl("[^8.]", L)
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE

# if we remove 8's and dot's there should be nothing left
nchar(gsub("[8.]", "", L)) == 0
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE

# trim off all 8's and dots and nothing should be left
!nzchar(trimws(L, whitespace = "[8.]"))
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
## [13] FALSE FALSE FALSE FALSE

Note

L <- c("888", "8", "8.88", "88.88", "88888.888", "899900", "8.89", 
"0.08", "80", "89899", "50", "32", "30.8", "0.081", "0.8", "8.1"
)

CodePudding user response:

Try

 grep("^8 ([.]8 )?$", as.character(num), value = TRUE)
[1] "888"       "8"         "8.88"      "88.88"     "88888.888"

CodePudding user response:

Maybe this works for you. Searching for one or more 8s, followed by zero or more . finally zero or more trailing 8s.

grep("^8 \\.*8*$", as.character(num), value=T)
[1] "888"       "8"         "8.88"      "88.88"     "88888.888"
  • Related