String.scan和String.split之间的区别

时间:2012-10-13 20:49:24

标签: ruby

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

1 个答案:

答案 0 :(得分:20)

它们服务于完全不同的目的。 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"]