11

Ruby 中这两个 (String#scan和) 有什么区别?String#split

4

1 回答 1

21

它们服务于完全不同的目的。 String#scan用于从字符串中提取正则表达式的匹配项并在数组中返回匹配项,而String#split旨在基于分隔符将字符串拆分为数组。定界符可以是静态字符串(例如;在单个分号上拆分)或正则表达式(例如/\s/+在任何空白字符上拆分)。

的输出String#split不包括分隔符。相反,除定界符之外的所有内容都将在输出数组中返回,而 的输出String#scan包括与定界符匹配的内容。

# A delimited string split on | returns everything surrounding the | delimiters
"a|delimited|string".split("|")
# Prints: ["a", "delimited", "string"]

# The same string scanninng for | only returns the matched |
"a|delimited|string".scan("|")
# Prints: ["|", "|"]

以上两种方法都可以接受一个正则表达式来代替简单的字符串"|"

# Split on everything between and including two t's
"a|delimited|string".split(/t.+t/)
# Prints: ["a|delimi", "ring"]

# Search for everything between and including two t's
"a|delimited|string".scan(/t.+t/)
# Prints: ["ted|st"]
于 2012-10-13T20:54:59.557 回答