使用R包装字符串,但不包括引号中的子字符串

And*_*rie 5 string word-wrap

这个问题与我关于Roxygen的问题有关.

我想编写一个新的函数,用于对字符串进行自动换行,类似于strwrap或者stringr::str_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\")"      
Run Code Online (Sandbox Code Playgroud)

我希望a的所需输出为newWrapFunction(x, width=40, ...):

desired <- c("function(x=123456789, ", "y=\"This is a long string argument\")")
desired
[1] "function(x=123456789, "               
[2] "y=\"This is a long string argument\")"

identical(desired, newWrapFunction(tsring, width=40))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

你能想到办法吗?


PS.如果你可以帮我解决这个问题,我会建议将这段代码作为补丁roxygen2.我已经确定了应该应用此补丁的位置,并将确认您的贡献.

42-*_*42- 2

这是我为获取 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) ...........
Run Code Online (Sandbox Code Playgroud)

然后最后将所有“~|~”替换为空格。可能需要更多地考虑其他类型的空白“事件”才能得到完全常规的治疗。

....
 y <- gsub("~\\|~", " ", y)
....
Run Code Online (Sandbox Code Playgroud)

编辑:测试了@joran的建议。对于我正在使用的方法来说,匹配单引号和双引号将是一项艰巨的任务,但如果愿意将任何引号视为与分隔符目标同等有效,则可以将其用作zz <- strsplit(x, "\'|\"")上面代码中的拆分标准。