我有这样的条件:
string <- "1, 2, \"something, else\""我想在tidyr::separate_rows()中使用sep==",",但是字符串引用部分中的逗号使我感到不舒服。我想删除事物和其他事物之间的逗号(但只有这个逗号)。
下面是一个更复杂的玩具示例:
string <- c("1, 2, \"something, else\"", "3, 5, \"more, more, more\"", "6, \"commas, are fun\", \"no, they are not\"")
string
#[1] "1, 2, \"something, else\""
#[2] "3, 5, \"more, more, more\""
#[3] "6, \"commas, are fun\", \"no, they are not\""我想去掉嵌入引号中的所有逗号。期望产出:
[1] "1, 2, \"something else\""
[2] "3, 5, \"more more more\""
[3] "6, \"commas are fun\", \"no they are not\""发布于 2022-11-18 12:47:23
您可以定义一个小函数来进行替换。
library(stringr)
rmcom <- function(x) gsub(",", "", x)
str_replace_all(string, "(\"[[:alnum:]]+,[ [:alnum:],]*\")", rmcom)
[1] "1, 2, \"something else\""
[2] "3, 5, \"more more more\""
[3] "6, \"commas are fun\", \"no they are not\""发布于 2022-11-18 12:36:36
我尽我所能:
stringr::str_replace_all(string,"(?<=\\\".{1,15})(,)(?=.+?\\\")","")它是:(?<= ) =向后看
\\\" =a \和a "
.{1,15} =1到15个字符(见注)
(,) =逗号是我们想要针对的
(?= )展望未来
.+? =一个或多个字符,但尽可能少
\\\" =a \和a "
注意:向后看不能是无限的,所以我们不能在这里使用.+?。为数据集调整15的最大值。
编辑:的解决方案更好--我愚蠢地忘记了"“定义字符串不是字符串的一部分,因此它比需要的要复杂得多。
发布于 2022-11-18 13:12:11
最后,我们可以反演这个问题(并保留逗号,这可能很有用),并直接使用separate_rows的正则表达式,只在逗号而不是引号中拆分:
library(tidyr)
df |>
separate_rows(stringcol, sep = '(?!\\B"[^\"]*), (?![^"]*\"\\B)')来自:Regex find comma not inside quotes的Regex表达式
另一种选择:Regex to pick characters outside of pair of quotes
输出:
# A tibble: 9 × 1
stringcol
<chr>
1 "1"
2 "2"
3 "\"something, else\""
4 "3"
5 "5"
6 "\"more, more, more\""
7 "6"
8 "\"commas, are fun\""
9 "\"no, they are not\""数据:
library(tibble)
df <- tibble(stringcol = string)https://stackoverflow.com/questions/74489132
复制相似问题