How to replace many special characters with “something plus special characters” in R

前端 未结 3 855
无人共我
无人共我 2020-12-21 11:27

I have this sentence that contains \"& / ?\".

c = \"Do Sam&Lilly like yes/no questions?\"

I want to add a whitespace before and af

3条回答
  •  轮回少年
    2020-12-21 12:05

    Seems like you mean this,

    > c <- "Do Sam&Lilly like yes/no questions?"
    > gsub("([^[:alnum:][:blank:]])", " \\1 ", c)
    [1] "Do Sam & Lilly like yes / no questions ? "
    

    [^[:alnum:][:blank:]] negated POSIX character class which matches any character but not of an alphanumeric or horizontal space character. BY putting the pattern inside a capturing group, it would capture all the special characters. Replacing the matched special chars with space+\\1 (refers the characters which are present inside the first group) + space will give you the desired output. You could use [:space:] instead of [:blank:] also.

提交回复
热议问题