我几乎在那里,但我被卡住了。我懂了,
string99 <- c("Foo /10", "Foo Bar 7 / 0", "FooBar 25 / 5", "I do 156 / ")
#> [1] "Foo /10" "Foo Bar 7 / 0" "FooBar 25 / 5" "I do 156 / "
gsub("[^[:alnum:][:space:]]",",",string99)
#> [1] "Foo ,10" "Foo Bar 7 , 0" "FooBar 25 , 5" "I do 156 , "
但我想要的是得到这个,
gsub(magic)
#> [1] "Foo, ,10" "Foo Bar,7 , 0" "FooBar,25 , 5" "I do,156 , "
额外的白色空间±并不是太重要,因为我正在从这里用read.csv
读,但是第一个逗号,只有当它在一个数字之前驱使我爬上墙。所以,我需要在每个字符串中使用两个逗号。任何帮助,将不胜感激!
更新,WiktorStribiżewlinked to some code below给出了这个结果
gsub("^\\D*?\\K(?=\\d+|/)|[^[:alnum:][:space:]]",",",string99, perl=TRUE)
#> [1] "Foo ,/10" "Foo Bar ,7 , 0" "FooBar ,25 , 5" "I do ,156 , "
更接近,但有一些正向斜线,/
,发生在"Foo ,/10"
,我想这是关于替换它为,
。
你可以用
string99 <- c("Foo /10", "Foo Bar 7 / 0", "FooBar 25 / 5", "I do 156 / ")
gsub("^([^\\d/]*)|[^[:alnum:][:space:]]","\\1,",string99, perl=TRUE)
要么
gsub("^([^\\d/]*)|[^\\w\\s]","\\1,",string99, perl=TRUE)
查看R demo和regex demo。
图案细节
^
- 字符串的开头([^\\d/]*)
之外的任何0+字符\1
- 或/
- 任何非单词和非空白字符。