【发布时间】: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'")
分割这个字符串的正确正则表达式是什么?
谢谢
【问题讨论】: