我试图strsplit()在R中使用基于逗号将字符串分解成碎片,但我不想在括号中拆分任何东西.我认为答案是正则表达式,但我正在努力使代码正确.
例如:
x <- "This is it, isn't it (well, yes)"
> strsplit(x, ", ")
[[1]]
[1] "This is it" "isn't it (well" "yes)"
Run Code Online (Sandbox Code Playgroud)
当我想要的是:
[1] "This is it" "isn't it (well, yes)"
Run Code Online (Sandbox Code Playgroud)
akr*_*run 15
我们可以使用PCRE正则表达式来FAIL任何,遵循一个(前)和斯普利特,后跟0或更多空间(\\s*)
strsplit(x, '\\([^)]+,(*SKIP)(*FAIL)|,\\s*', perl=TRUE)[[1]]
#[1] "This is it" "isn't it (well, yes)"
Run Code Online (Sandbox Code Playgroud)
我建议使用另一个正则表达式(*SKIP)(*F)来忽略所有(...)子字符串,并且只匹配带括号的子字符串之外的逗号:
x <- "This is it, isn't it (well, yes), and (well, this, that, and this, too)"
strsplit(x, "\\([^()]*\\)(*SKIP)(*F)|\\h*,\\h*", perl=T)
Run Code Online (Sandbox Code Playgroud)
请参阅IDEONE演示
您可以阅读有关如何(*SKIP)或(*F)在正则表达式上工作的更多信息?这里.正则表达式匹配:
\( - 一个开口支架[^()]*-比其他零个或多个字符(和)\) - 一个结束括号(*SKIP)(*F) - 将当前正则表达式索引推进到结束括号之后的位置的动词| - 要么...\\h*,\\h* - 包含零个或多个水平空格的逗号.