加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中拆分字符串,忽略括号内容?

发布时间:2020-12-17 04:25:08 所属栏目:百科 来源:网络整理
导读:我需要在 Ruby中将一个字符串拆分成一个部分列表,但是我需要忽略paramentheses中的内容.例如: A +4,B +6,C (hello,goodbye) +5,D +3 我希望结果列表是: [0]A +4[1]B +6[2]C (hello,goodbye) +5[3]D +3 但我不能简单地用逗号分割,因为这会分割括号的内容.有
我需要在 Ruby中将一个字符串拆分成一个部分列表,但是我需要忽略paramentheses中的内容.例如:
A +4,B +6,C (hello,goodbye) +5,D +3

我希望结果列表是:

[0]A +4
[1]B +6
[2]C (hello,goodbye) +5
[3]D +3

但我不能简单地用逗号分割,因为这会分割括号的内容.有没有办法在没有预先解析大括号中的逗号的情况下拆分东西?

谢谢.

解决方法

试试这个:
s = 'A +4,D +3'
tokens = s.scan(/(?:(.*?)|[^,])+/)
tokens.each {|t| puts t.strip}

输出:

A +4
B +6
C (hello,goodbye) +5
D +3

一个简短的解释:

(?:        # open non-capturing group 1
  (       #   match '('
  .*?      #   reluctatly match zero or more character other than line breaks
  )       #   match ')'
  |        #   OR
  [^,]     #   match something other than a comma
)+         # close non-capturing group 1 and repeat it one or more times

另一种选择是,只有当向前看时可以看到的第一个括号是一个左括号(或根本没有括号:即字符串的结尾)时,才能在逗号后面跟上一些空格:

s = 'A +4,D +3'
tokens = s.split(/,s*(?=[^()]*(?:(|$))/)
tokens.each {|t| puts t}

将产生相同的输出,但我发现扫描方法更清洁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读