【问题标题】:Split R string at spaces but not when the space is between single quotes在空格处拆分 R 字符串,但在空格位于单引号之间时不拆分
【发布时间】:2020-03-18 12:42:35
【问题描述】:

我有一组丑陋而复杂的字符串,我必须拆分:

vec <- c("'01'", "'01' '02'", 
         "#bateau", "#bateau #batiment",
         "#'autres 32'", "#'autres 32' #'batiment 30'", "#'autres 32' #'batiment 30' #'contenu 31'",
         "#'34'", "#'34' #'33' #'35'")
vec
[1] "'01'"                                      "'01' '02'"                                
[3] "#bateau"                                   "#bateau #batiment"                        
[5] "#'autres 32'"                              "#'autres 32' #'batiment 30'"              
[7] "#'autres 32' #'batiment 30' #'contenu 31'" "#'34'"                                    
[9] "#'34' #'33' #'35'" 

我需要在有空格的地方分割字符串 (),除非空格在 ' 之间。所以在上面的例子中,'01' '02' 会变成 '01''02'#'autres 32' #'batiment 30' 会变成 #'autres 32'#'batiment 30'

我尝试从this question 获得灵感,但没有走多远:

strsplit(vec, "(\\s[^']+?)('.*?'|$)")

因为这个解决方案分割了一些不应该的空间,也让我失去了一些信息。

拆分的结果应该是这样的:

res <- c("'01'", "'01'", "'02'", 
         "#bateau", "#bateau", "#batiment",
         "#'autres 32'", "#'autres 32'", "#'batiment 30'", "#'autres 32'", "#'batiment 30'", "#'contenu 31'",
         "#'34'", "#'34'", "#'33'", "#'35'")

分割这个字符串的正确正则表达式是什么?

谢谢

【问题讨论】:

    标签: r regex


    【解决方案1】:

    你可以使用

    strsplit(vec, "'[^']*'(*SKIP)(*F)|\\s+", perl=TRUE)
    

    在线查看R demoregex demo

    详情

    • '[^']*'(*SKIP)(*F) - ',然后是除 ' 之外的任何 0+ 个字符(参见 [^']*),然后是 ',然后丢弃此匹配的文本并从当前匹配的位置搜索下一个匹配匹配失败(见(*SKIP)(*F)
    • | - 或
    • \s+ - 1+ 个空格字符。

    由于它是 PCRE 模式,perl=TRUE 是强制性的。

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多