String 使用R将字符串(而不是子字符串)括在引号中

String 使用R将字符串(而不是子字符串)括在引号中,string,word-wrap,String,Word Wrap,这个问题与我的工作有关 我想编写一个新函数,对字符串进行文字换行,类似于strwrap或stringr::stru wrap,但有以下扭曲:字符串中包含在引号中的任何元素(子字符串)都不能换行。 例如,使用以下示例数据 test <- "function(x=123456789, y=\"This is a long string argument\")" cat(test) function(x=123456789, y="This is a long string argument")

这个问题与我的工作有关

我想编写一个新函数,对字符串进行文字换行,类似于
strwrap
stringr::stru wrap
,但有以下扭曲:字符串中包含在引号中的任何元素(子字符串)都不能换行。

例如,使用以下示例数据

test <- "function(x=123456789, y=\"This is a long string argument\")"
cat(test)
function(x=123456789, y="This is a long string argument")

strwrap(test, width=40)
[1] "function(x=123456789, y=\"This is a long"
[2] "string argument\")"      
你能想出一个办法吗



注:如果你能帮我解决这个问题,我将把这个代码作为
roxygen2
的补丁。我已确定此修补程序应应用于何处,并将感谢您的贡献。

以下是我为获得strwrap所做的工作,这样它就不会破坏空格上的单个引用部分: A) 通过用“~ | ~”替换空格,预处理按单引号拆分后的“偶数”部分: 定义新函数strwrapqt

 ....  
 zz <- strsplit(x, "\'") # will be only working on even numbered sections
   for (i in seq_along(zz) ){ 
       for (evens in seq(2, length(zz[[i]]), by=2)) {
            zz[[i]][evens] <- gsub("[ ]", "~|~", zz[[i]][evens])}
                       }
 zz <- unlist(zz) 
  .... insert just before
 z <- lapply(strsplit) ...........
。。。。

齐了@Andrie没有指定单引号和双引号,但也许在“\'\”上拆分是个好主意?不知道如何处理双引号段中的单引号(例如撇号)。@joran:让我们看看我的正则表达式fu是否能胜任这一挑战。我肯定会把混合引号问题(混乱?)留到另一天。
 ....  
 zz <- strsplit(x, "\'") # will be only working on even numbered sections
   for (i in seq_along(zz) ){ 
       for (evens in seq(2, length(zz[[i]]), by=2)) {
            zz[[i]][evens] <- gsub("[ ]", "~|~", zz[[i]][evens])}
                       }
 zz <- unlist(zz) 
  .... insert just before
 z <- lapply(strsplit) ...........
....
 y <- gsub("~\\|~", " ", y)
....