我快到了,但我被困住了。我明白了,
core
但我希望得到这个,
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 , "
读取,但是第一个逗号,只有当它在一个数字之前驱动我上升时。所以,我需要在每个字符串中使用两个逗号。任何帮助,将不胜感激!
更新,WiktorStribiżewlinked to some code below提供此结果
read.csv
更接近,但在gsub("^\\D*?\\K(?=\\d+|/)|[^[:alnum:][:space:]]",",",string99, perl=TRUE)
#> [1] "Foo ,/10" "Foo Bar ,7 , 0" "FooBar ,25 , 5" "I do ,156 , "
中发生了一些正斜杠,/
,我想这是用"Foo ,/10"
代替它。
答案 0 :(得分:1)
您可以使用
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/]*)
- 捕获组#1(使用\1
占位符从替换模式引用):除数字和/
之外的任何0+字符|
- 或[^\\w\\s]
- 任何非单词和非空白字符。