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

在Ruby中拆分字符串,忽略括号的内容?,ruby,string,split,Ruby,String,Split,我需要在Ruby中将一个字符串拆分成一个部分列表,但我需要忽略参数sees中的内容。例如: 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, B +6, C (hello,

我需要在Ruby中将一个字符串拆分成一个部分列表,但我需要忽略参数sees中的内容。例如:

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, B +6, C (hello, goodbye) +5, 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
另一种选择是,仅当向前看时可以看到的第一个括号是一个左括号(或者根本没有括号:即字符串的结尾)时,才在逗号后面加上一些空格进行拆分:

将产生相同的输出,但我发现
scan
方法更干净

string = "A +4, B +6, C (hello, goodbye) +5, D +3"
string.split(/ *, *(?=[^\)]*?(?:\(|$))/)
# => ["A +4", "B +6", "C (hello, goodbye) +5", "D +3"]
此正则表达式的工作原理:

/
   *, *        # find comma, ignoring leading and trailing spaces.
  (?=          # (Pattern in here is matched against but is not returned as part of the match.)
    [^\)]*?    #   optionally, find a sequence of zero or more characters that are not ')'
    (?:        #   <non-capturing parentheses group>
      \(       #     left paren ')'
      |        #     - OR -
      $        #     (end of string)
    )
  )
/
/
*,*#查找逗号,忽略前导空格和尾随空格。
(?=#)(此处的模式匹配,但不作为匹配的一部分返回。)
[^\)]*?    #   (可选)查找不为“')的零个或多个字符序列
(?:        #   
\(#左paren')”
|#-或-
$#(字符串末尾)
)
)
/

当心皱眉的脸:-(搞乱了解析!#=>[“A+4”、“B+6”、“C(你好,再见)+5”、“D+3”]对我来说很完美。可能需要修剪它以删除周围的空白。这对
A+4、B+6、C(你好,(你好吗?、糟糕)再见)不起作用)+5,D+3
。你知道如何修复它吗?@rochb,当任意数量的嵌套括号起作用时,请使用适当的解析器,不要使用正则表达式进行黑客攻击。如果没有对胆小的正则表达式爱好者的解释,这可能有点晦涩(操作可能是!)。不过,这是一个很好的解决方案。它是如何工作的?我找不到任何关于regex如何与split一起工作的好文档,就像Bart K说的,我对split不是很在行regexes@Colen,我发布了一个非常类似的正则表达式作为第二个解决方案,包括一个解释。
/
   *, *        # find comma, ignoring leading and trailing spaces.
  (?=          # (Pattern in here is matched against but is not returned as part of the match.)
    [^\)]*?    #   optionally, find a sequence of zero or more characters that are not ')'
    (?:        #   <non-capturing parentheses group>
      \(       #     left paren ')'
      |        #     - OR -
      $        #     (end of string)
    )
  )
/