如何用“东西加特殊字符"替换许多特殊字符在 R [英] How to replace many special characters with "something plus special characters" in R
问题描述
我有这句话包含&/?".
I have this sentence that contains "& / ?".
c = "Do Sam&Lilly like yes/no questions?"
我想在要获取的每个特殊字符前后添加一个空格
I want to add a whitespace before and after each of the special characters to get
"Do Sam & Lilly like yes / no questions ? "
我只能通过艰难的方式得到这个:
I can only get this by the hard way:
c = gsub("[&]", " & ", c)
c = gsub("[/]", " / ", c)
c = gsub("[?]", " ? ", c)
但是想象一下,我有很多这样的特殊字符,这需要使用 [:alnum:].所以我真的在寻找一个看起来像这样的解决方案:
But imagine that I have many of these special character, which warrants using [:alnum:]. So I am really looking for a solution that looks like this:
gsub("[[:alnum:]]", " [[:alnum:]] ", c)
不幸的是,我不能以这种方式使用 [:alnum:] 作为第二个参数.
Unfortunately, I cannot use [:alnum:] as the second argument this way.
推荐答案
您可以使用捕获组引用:
You can use a capture group reference:
gsub("([&/])", " \\1 ", c)
这里我们将 "&"
或 "/"
替换为它们自己 ("\\1"
) 填充空格."\\1"
表示使用模式中的第一个匹配组.匹配组是括号中正则表达式的一部分.在我们的例子中,"([&/])"
.
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.
注意:您可能不应该使用 c
作为变量名,因为它也是一个非常常用的函数的名称.
note: you probably shouldn't use c
as a variable name since it is also the name of a very commonly used function.
这篇关于如何用“东西加特殊字符"替换许多特殊字符在 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!