Ruby "hello world" .scan (/ (\ w) {2} /) does not match "hello world" .scan (/ \ w {2} /)?

I thought I knew scanin Ruby: as if it were doing one match, but repeating it for all the results and putting it into an array?

ruby-1.9.2-p0 > "hello world".scan(/\w{2}/)
 => ["he", "ll", "wo", "rl"] 

ruby-1.9.2-p0 > "hello world".scan(/(\w){2}/)
 => [["e"], ["l"], ["o"], ["l"]] 

How did it happen that the second line led to the fact that and how do you return the same result as line 1? (because sometimes we need to add ()to the regular expression.


as a contract, with or without (), the same:

ruby-1.9.2-p0 > "hello world"[/\w{2}/]
 => "he" 

ruby-1.9.2-p0 > "hello world"[/(\w){2}/]
 => "he" 
+3
source share
2 answers

Paranas create a matching group. Try it instead /(?:\w){2}/.

+3
source

I found something else:

scan, , , , 2- . ( ( ) .)

: ( , )

ruby-1.9.2-p0 > "hello world".scan(/((\w){2})/)
 => [["he", "e"], ["ll", "l"], ["wo", "o"], ["rl", "l"]] 

: alway ( ) map, ( ):

ruby-1.9.2-p0 > "hello world".scan(/((\w){2})/).map {|e| e.first}
 => ["he", "ll", "wo", "rl"]

...

0

Source: https://habr.com/ru/post/1773384/


All Articles