String.scan 和 String.split 的区别 [英] Difference between String.scan and String.split
问题描述
Ruby 中这两个(String#scan
和 String#split
)有什么区别?
What is the difference between these two (String#scan
and String#split
) in Ruby?
推荐答案
它们的用途完全不同.使用 String#scan
从字符串中提取正则表达式的匹配项并返回数组中的匹配项,而 String#split
旨在根据分隔符将字符串拆分为数组.分隔符可以是一个静态字符串(如 ;
在单个分号上拆分)或正则表达式(如 /\s/+
在任何空白字符上拆分).
They serve entirely different purposes. String#scan
is used to extract matches of a regular expression from a string and return the matches in an array, while String#split
is intended to split a string up into an array, based on a delimiter. The delimiter may be either a static string (like ;
to split on a single semicolon) or a regular expression (like /\s/+
to split on any whitespace characters).
String#split
的输出不包括分隔符.相反,除分隔符之外的所有内容都将在输出数组中返回,而 String#scan
的输出将只包括与分隔符匹配的内容.
The output of String#split
doesn't include the delimiter. Rather, everything except the delimiter would be returned in the output array, while the output of String#scan
would only include what is matched by the delimiter.
# 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: ["|", "|"]
以上两种方法也都接受一个正则表达式来代替简单的字符串 "|"
.
Both of the above would also accept a regular expression in place of the simple string "|"
.
# 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"]
这篇关于String.scan 和 String.split 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!