r 在分隔符上拆分而不是在括号中 [英] r split on delimiter not in parentheses

查看:41
本文介绍了r 在分隔符上拆分而不是在括号中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在管道分隔符上拆分字符串:

I am currently trying to split a string on the pipe delimiter: 

999|150|222|(123|145)|456|12,260|(10|10000)

问题是我不想在括号内的 | 上拆分,我只想在括号外的这个字符上拆分.

The catch is I don't want to split on | inside of parentheses, I only want to split on this character outside of parentheses.

这只是拆分每个 | 字符,产生我不想要的结果:

This is just splitting on every | character, yielding the results I don't want:

x <- '999|150|222|(123|145)|456|12,260|(10|10000)'
m <- strsplit(x, '\\|')

[[1]]
[1] "999"    "150"    "222"    "(123"   "145)"   "456"    "12,260" "(10"   
[9] "10000)"

我希望得到以下结果,将所有内容都放在括号内:

I am looking to get the following results keeping everything inside of parentheses:

[[1]]
[1] "999"        "150"        "222"        "(123|145)"  "456"       
[6] "12,260"     "(10|10000)"

感谢任何帮助.

推荐答案

您可以打开PCRE 使用 perl=T 和一些黑魔法:

You can switch on PCRE by using perl=T and some dark magic:

x <- '999|150|222|(123|145)|456|12,260|(10|10000)'
strsplit(x, '\\([^)]*\\)(*SKIP)(*F)|\\|', perl=T)

# [[1]]
# [1] "999"        "150"        "222"        "(123|145)"  "456"       
# [6] "12,260"     "(10|10000)"

这个想法是跳过括号中的内容.现场演示

The idea is to skip content in parentheses. Live demo

替代运算符的左侧,我们匹配括号中的任何内容使子模式失败并强制正则表达式引擎不使用回溯控制重试子字符串.交替运算符的右侧匹配 |(括号外,我们想要的...)

On the left side of the alternation operator we match anything in parentheses making the subpattern fail and force the regular expression engine to not retry the substring using backtracking control. The right side of the alternation operator matches | (outside of parentheses, what we want...)

这篇关于r 在分隔符上拆分而不是在括号中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆