[a-z]和[0-9]之间的RegEx空间

时间:2018-04-23 20:05:48

标签: r regex gsub

我快到了,但我被困住了。我明白了,

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"代替它。

1 个答案:

答案 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 demoregex demo

模式详情

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