I have a string say \"a.b\" and I want to replace \".\" with \"_\".
gsub(\".\",\"_\",\"a.b\")
doesn\'t work as . matches all characters.
Try [[:punct:]] regex syntax, as "." in itself is a punctuation character present in the string.
gsub("[[:punct:]]","_","a.b")
Output : [1] "a_b"
.
matches any character. Escape .
using \
to match .
literally.
\
itself is also should be escaped:
> gsub("\\.", "_", "a.b")
[1] "a_b"
You need to double escape \\
, escaping .
to match the literal dot and escaping \
also. Keep in mind using sub
replaces the first occurrence of a pattern, gsub
replaces all occurrences.
string <- "a.b"
sub('\\.', '_', string)
[1] "a_b"
string <- "a.b.c.d.e.f"
gsub('\\.', '_', string)
[1] "a_b_c_d_e_f"
You can also use sub
or gsub
with the fixed = TRUE
parameter. This takes the string representing the pattern you are searching for as it is ignoring special characters.
string <- "a.b"
sub('.', '_', string, fixed = TRUE)
[1] "a_b"
try like this :
gsub("[.]","_","a.b")