Reputation: 3937
Why does the second split
in the following return the punctuation? Why does using parentheses in the regular expression change the output?
str = "This is a test string. Let's split it."
str.split(/\. /)
# =>["This is a test string", "Let's split it."]
str.split(/(\. )/)
# =>["This is a test string", ". ", "Let's split it."]
Upvotes: 2
Views: 53
Reputation: 122383
Because the second code uses a regex that contains a group. From String#split
:
If pattern is a
Regexp
,str
is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.
Upvotes: 1