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

前端 未结 3 852
无人共我
无人共我 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:10

    You can use a capture group reference:

    gsub("([&/])", " \\1 ", c)
    

    Here we replace "&" or "/" with themselves ("\\1") padded with spaces. The "\\1" means "use the first matched group from the pattern. A matched group is a portion of a regular expression in parentheses. In our case, the "([&/])".

    You can expand this to cover more symbols / special characters by adding them to the character set, or by putting in an appropriate regex special character.

    note: you probably shouldn't use c as a variable name since it is also the name of a very commonly used function.

提交回复
热议问题