[a-z] 和 [0-9] 之间的正则表达式 space

RegEx space between [a-z] and [0-9]

我快到了,但我卡住了。我明白了,

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 , "  

额外的白色 space± 并不太重要,因为我正在阅读这里的 read.csv,但是第一个逗号,只有在数字之前才会驱使我墙。所以,我需要在每个字符串中使用两个逗号。任何帮助,将不胜感激!

更新,Wiktor Stribiżew 给出了这个结果

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 and a regex demo

图案详情

  • ^ - 字符串开头
  • ([^\d/]*) - 捕获第 1 组(使用 </code> 占位符从替换模式中引用):除数字和 <code>/
  • 之外的任何 0+ 个字符
  • | - 或
  • [^\w\s] - 任何非单词和非空白字符。