aceofbassgreg
aceofbassgreg

Reputation: 3937

Different return values of `String#split` method using regex

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

Answers (1)

Yu Hao
Yu Hao

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

Related Questions