instance method
String#scan
(::Regexp pattern) -> ::Array[::String | ::Array[::String?]]
(::Regexp pattern) { (::String | ::Array[::String?] matches) -> void } -> self
(::string pattern) -> ::Array[::String]
(::string pattern) { (::String match) -> void } -> self
scan(pattern) → array_of_results
scan(pattern) {|result| ... } → self
string.c
View on GitHub ↗
static VALUE
rb_str_scan(VALUE str, VALUE pat)
{
VALUE result;
long start = 0;
long last = -1, prev = 0;
char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str);
pat = get_pat_quoted(pat, 1);
mustnot_broken(str);
if (!rb_block_given_p()) {
VALUE ary = rb_ary_new();
while (!NIL_P(result = scan_once(str, pat, &start, 0))) {
last = prev;
prev = start;
rb_ary_push(ary, result);
}
if (last >= 0) rb_pat_search(pat, str, last, 1);
else rb_backref_set(Qnil);
return ary;
}
while (!NIL_P(result = scan_once(str, pat, &start, 1))) {
last = prev;
prev = start;
rb_yield(result);
str_mod_check(str, p, len);
}
if (last >= 0) rb_pat_search(pat, str, last, 1);
return str;
}
Matches a pattern against self:
-
If
patternis aRegexp, the pattern used ispatternitself. -
If
patternis a string, the pattern used isRegexp.quote(pattern).
Generates a collection of matching results and updates regexp-related global variables:
-
If the pattern contains no groups, each result is a matched substring.
-
If the pattern contains groups, each result is an array containing a matched substring for each group.
With no block given, returns an array of the results:
Example
'cruel world'.scan(/\w+/) # => ["cruel", "world"] 'cruel world'.scan(/.../) # => ["cru", "el ", "wor"] 'cruel world'.scan(/(...)/) # => [["cru"], ["el "], ["wor"]] 'cruel world'.scan(/(..)(..)/) # => [["cr", "ue"], ["l ", "wo"]] 'тест'.scan(/../) # => ["те", "ст"] 'こんにちは'.scan(/../) # => ["こん", "にち"] 'abracadabra'.scan('ab') # => ["ab", "ab"] 'abracadabra'.scan('nosuch') # => []
With a block given, calls the block with each result; returns self:
Example
'cruel world'.scan(/\w+/) {|w| p w } # => "cruel" # => "world" 'cruel world'.scan(/(.)(.)/) {|x, y| p [x, y] } # => ["c", "r"] # => ["u", "e"] # => ["l", " "] # => ["w", "o"] # => ["r", "l"]
Related: see Converting to Non-String.