R: How to replace . in a string?

前端 未结 4 680
旧巷少年郎
旧巷少年郎 2020-12-11 14:33

I have a string say \"a.b\" and I want to replace \".\" with \"_\".

gsub(\".\",\"_\",\"a.b\")

doesn\'t work as . matches all characters.

相关标签:
4条回答
  • 2020-12-11 15:18

    Try [[:punct:]] regex syntax, as "." in itself is a punctuation character present in the string.

    gsub("[[:punct:]]","_","a.b")
    

    Output : [1] "a_b"

    0 讨论(0)
  • 2020-12-11 15:22

    . matches any character. Escape . using \ to match . literally.

    \ itself is also should be escaped:

    > gsub("\\.", "_", "a.b")
    [1] "a_b"
    
    0 讨论(0)
  • 2020-12-11 15:24

    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"
    
    0 讨论(0)
  • 2020-12-11 15:27

    try like this :

    gsub("[.]","_","a.b")
    
    0 讨论(0)
提交回复
热议问题