首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >删除逗号内引号

删除逗号内引号
EN

Stack Overflow用户
提问于 2022-11-18 11:41:48
回答 3查看 291关注 0票数 7

我有这样的条件:

代码语言:javascript
复制
string <- "1, 2, \"something, else\""

我想在tidyr::separate_rows()中使用sep==",",但是字符串引用部分中的逗号使我感到不舒服。我想删除事物和其他事物之间的逗号(但只有这个逗号)。

下面是一个更复杂的玩具示例:

代码语言:javascript
复制
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\""

我想去掉嵌入引号中的所有逗号。期望产出:

代码语言:javascript
复制
[1] "1, 2, \"something else\""                  
[2] "3, 5, \"more more more\""                  
[3] "6, \"commas are fun\", \"no they are not\""
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-11-18 12:47:23

您可以定义一个小函数来进行替换。

代码语言:javascript
复制
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\""
票数 8
EN

Stack Overflow用户

发布于 2022-11-18 12:36:36

我尽我所能:

代码语言:javascript
复制
stringr::str_replace_all(string,"(?<=\\\".{1,15})(,)(?=.+?\\\")","")

它是:(?<= ) =向后看

\\\" =a \和a "

.{1,15} =1到15个字符(见注)

(,) =逗号是我们想要针对的

(?= )展望未来

.+? =一个或多个字符,但尽可能少

\\\" =a \和a "

注意:向后看不能是无限的,所以我们不能在这里使用.+?。为数据集调整15的最大值。

编辑:的解决方案更好--我愚蠢地忘记了"“定义字符串不是字符串的一部分,因此它比需要的要复杂得多。

票数 3
EN

Stack Overflow用户

发布于 2022-11-18 13:12:11

最后,我们可以反演这个问题(并保留逗号,这可能很有用),并直接使用separate_rows的正则表达式,只在逗号而不是引号中拆分:

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
# 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\""

数据:

代码语言:javascript
复制
library(tibble)

df <- tibble(stringcol = string)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74489132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档