Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
条件替换为str_替换_R_Regex - Fatal编程技术网

条件替换为str_替换

条件替换为str_替换,r,regex,R,Regex,我有这样的数据: d = as.character(c("1,23", "1,23.23", "1.23", "-1.2", "1,23.234")) 如果字符串有标点符号和逗号,我想删除标点符号后面的字符和标点符号本身 结果应该如下所示: d = as.character(c("1,23", "1,23", "1.23", "-1.2", "1,23")) 问题是我不能使用str_replace,因为它还会删除其他字符串 library(stringr) str_replace(d,

我有这样的数据:

d = as.character(c("1,23", "1,23.23", "1.23", "-1.2", "1,23.234"))
如果字符串有标点符号和逗号,我想删除标点符号后面的字符和标点符号本身

结果应该如下所示:

 d = as.character(c("1,23", "1,23", "1.23", "-1.2", "1,23")) 
问题是我不能使用str_replace,因为它还会删除其他字符串

library(stringr)

str_replace(d,"\\.[0-9]+", "")
[1] "1,23" "1,23" "1"    "-1"   "1,23"

我们可以将一个或多个数字后跟逗号或点的模式与一个或多个数字匹配,作为一个组捕获(
(…)
),并在替换中使用组的反向引用(
\\1

sub("^(-?\\d+[,.]\\d+).*", "\\1", d)
#[1] "1,23" "1,23" "1.23" "-1.2" "1,23"

或者在
str\u replace

library(stringr)
str_replace(d, "^(-?\\d+[,.]\\d+).*", "\\1")
#[1] "1,23" "1,23" "1.23" "-1.2" "1,23"

由于我们的数据似乎有效,如果可以使用lookaround,则此表达式可能有效:

(?<=,)(.+)(\..+)
(?
str_replace(d, "(?<=,)(.+)(\..+)", "\\1")
sub("(?<=,)(.+)(\..+)", "\\1", d)