pnb1
pnb1

Reputation: 43

Ruby ReGex Split at nth new line

I have this text:

str = "

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.
This is line 7.
This is line 8.
This is line 9.
This is line 10."

In ruby I want to make an array of this text split by every 3rd new line.

arr = ["This is line 1.
    This is line 2.
    This is line 3.",

    "This is line 4.
    This is line 5.
    This is line 6.",

    "This is line 7.
    This is line 8.
    This is line 9.",

    "This is line 10."]

I can't get a correct RegEx rule to accomplish it. So far I got

arr = str.split(/((?:.*)\n){3}/)

Unfortunately it matches not only 3rd line's \n but also the text before it. It would be great if somehow i could exclude that text

Upvotes: 0

Views: 446

Answers (5)

spickermann
spickermann

Reputation: 107037

This might not be as fancy as an regexp, but perhaps it is easier to understand...

string.split(/\n/).each_slice(3).map { |slice| slice.join("\n") }

Upvotes: 2

emartinelli
emartinelli

Reputation: 1047

Use capturing groups

((?:(?:.*)\n){3})|(.*)$

Groups 1 and 2 will return what you need

DEMO - Regex101 DEMO - Rubular

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107347

You can use following regex :

(\n?[^\n]*\n[^\n]*\n[^\n]*)

http://rubular.com/r/f2at0uX3D2

Note that instead of .* you need to use [^\n]* that will match any thing except newline.

Or more precise :

((?:[^\n]*\n){3})

Upvotes: 1

karthik manchala
karthik manchala

Reputation: 13640

Your regex is almost correct.. just include correct capture groups:

((?:(?:.*)\n){3})
^ ^^            ^

See DEMO

Upvotes: 1

vks
vks

Reputation: 67988

((?:[^\n]*\n){3})

Split by this.See demo.

https://regex101.com/r/pG1kU1/14

Upvotes: 1

Related Questions