I would like to replace all characters after the first two digits after a dot.
E.g. having a string of 1234.56789
should result into 1234.56
.
I have been trying "str_replace" but I could not write a regular expression to make it right.
I would like to replace all characters after the first two digits after a dot.
E.g. having a string of 1234.56789
should result into 1234.56
.
I have been trying "str_replace" but I could not write a regular expression to make it right.
like this?
library(stringr)
x <- '1234.56789'
stringr::str_replace(x,"(?<=\\.\\d\\d)(.*)$","")
#> [1] "1234.56"
Created on 2023-08-31 with reprex v2.0.2
if you need this for digits before and after a dot, then this
str_replace(x,
pattern = "(\\.[0-9]{2})[0-9]*",
replacement = "\\1")
whereas if its alphanumeric character then perhaps
str_replace(x,
pattern = "(\\.[[:alnum:]]{2})[[:alnum:]]*",
replacement = "\\1")
Thanks a lot for the answers. They work perfectly!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.