Regex to find string with optional "final" dot (and no more)

Viewed 199

I am getting frustrated about how to correctly add an optional "final" full stop / period / dot to a string in a regex. I am looking to find a string with an optional dot. If there is anything else, this should not be returned.

I tried approaches suggested in

x <- c("string", "string.", "string. and other")

grepl("string(?=\\.)", x, perl = TRUE)
#> [1] FALSE  TRUE  TRUE
grepl("string(\\.?)", x, perl = TRUE)
#> [1] TRUE TRUE TRUE
grepl("string(\\.)?", x, perl = TRUE)
#> [1] TRUE TRUE TRUE
grepl("string(\\.$)?", x, perl = TRUE)
#> [1] TRUE TRUE TRUE

#desired output 
c(TRUE, TRUE, FALSE)
#> [1]  TRUE  TRUE FALSE

Created on 2021-03-28 by the reprex package (v1.0.0)

1 Answers

You can use

grepl("^[^.]*\\.?$", x)
## => [1]  TRUE  TRUE FALSE

Details:

  • ^ - start of string
  • [^.]* - zero or more chars other than a dot
  • \.? - an optional dot
  • $ - end of string.

See the regex demo and an R demo online.

Related