`
sunwinner
  • 浏览: 203080 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Trapped by String#split of Ruby

    博客分类:
  • 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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics