remove comma from a digits portion string
我怎样才能(最快最好)从字符串的数字部分删除逗号而不影响字符串中的其余逗号。因此,在下面的示例中,我想从数字部分中删除逗号,但 dog 后面的逗号应该保留(是的,我知道 1023455 中的逗号是错误的,但只是扔了一个角盒)。
我有什么:
1 | x <-"I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away" |
期望的结果:
1 | [1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" |
规定:必须在base no add on packages中完成。
提前谢谢你。
编辑:
谢谢 Dason、Greg 和 Dirk。你的两个回答都很好。我正在玩一些接近 Dason 的反应的东西,但括号内有逗号。现在再看也觉得没有道理。我对这两个响应进行了微基准测试,因为我需要速度(文本数据):
1 2 3 4 5 6 7 | Unit: microseconds expr min lq median uq max 1 Dason_0to9 14.461 15.395 15.861 16.328 25.191 2 Dason_digit 21.926 23.791 24.258 24.725 65.777 3 Dirk 127.354 128.287 128.754 129.686 154.410 4 Greg_1 18.193 19.126 19.127 19.594 27.990 5 Greg_2 125.021 125.954 126.421 127.353 185.666 |
1 给你们。
您可以用数字本身替换任何带有模式(逗号后跟数字)的内容。
1 2 3 4 5 6 | x <-"I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away" gsub(",([[:digit:]])","\\\\1", x) #[1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" #or gsub(",([0-9])","\\\\1", x) #[1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" |
使用 Perl 正则表达式,并专注于"数字逗号数字",然后我们只用数字替换:
1 2 3 4 | R> x <-"I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away" R> gsub("(\\\\d),(\\\\d)","\\\\1\\\\2", x, perl=TRUE) [1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" R> |
这里有几个选项:
1 2 3 4 5 6 | > tmp <-"I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away" > gsub('([0-9]),([0-9])','\\\\1\\\\2', tmp ) [1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" > gsub('(?<=\\\\d),(?=\\\\d)','',tmp, perl=TRUE) [1]"I want to see 1023455 dogs, but not too soo; it's 3242 minutes away" > |
它们都匹配一个数字,后跟一个逗号,后跟一个数字。
第一个 epression 捕获逗号之前的数字和逗号之后的数字,并在替换字符串中使用它们。基本上把它们拉出来再放回去(但不把逗号放回去)。
第二个版本使用零长度匹配,