Trapped by String#split of Ruby

Today I was trapped by kind of wierd behavior of Ruby's String#split, here's an example:

def parse_inline_styles(text)
  segments = text.split(%r{(</?.*?>)}).reject {|x| x.empty?}
  segments.size == 1 ? segments.first : segments
end

This code snippet parse text string by <b>, </b>, <i>,</i>, which is specified by regular expression %r{(</?.*?>)}, the result is an array of parsed string. The caveat is the capturing grouping, if we miss the capture group, the String#split() will behavior differently. Let's see thr RDoc from Ruby core.

 

split(pattern=$;, [limit]) → anArray

click to toggle source

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

 

When the input str is empty an empty Array is returned as the string is considered to have no fields to split.

 

It says that: If pattern contains groups, the respective matches will be returned in the array as well. Let's verify it with another simple code snippet:

2.0.0p247 :013 > "a<b>bc".split(/<b>/)
 => ["a", "bc"] 
2.0.0p247 :014 > "a<b>bc".split(/(<b>)/)
 => ["a", "<b>", "bc"] 
2.0.0p247 :015 > 

The behavior of String#split is just as the RDoc described, it's kind of wired from a Java developer's eyes, which never include matched result of regex

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值