2017-09-29 3 views
2

n番目の改行ごとに文字列を分割するソリューションを探しています。 は、私はn番目の文字でそれを行うためのソリューションを見つけた私は私にjavadriptを使用してn回目の改行ごとに文字列を分割する

"One\nTwo\nThree\n" and "Four\nFive\nSix\n" 

のようなものを与えるだろう6行

"One\nTwo\nThree\nFour\nFive\nSix\n" 

だから、3行目の破断分割を持っている1つの文字列を持っていると言うことができますが、私n番目の改行がどのような文字の長さで起こるのかを明確にすることはできません。 私の質問がはっきりしていることを願っています。おかげさまで

+0

少なくとも3行を一致させよう、分割しようとしないでください。 –

+0

@CasimiretHippolyteこれを行う方法があまりわからない、複数の行に一致するパターンが見つかり、n個の行数ごとに一致するパターンを見つけるのに問題があります。 –

+1

@HaiderAliこの場合、入力が 'One \ n \ n \ n \ n \ nTwo \ n \ nThree \ n \ nFour \ n \ nFive \ n \ n \ n \ n' nSix \ n'? – Gurman

答えて

2

代わりString.prototype.splitを使用しての、それはString.prototype.matchメソッドを使用する方が簡単です:

"One\nTwo\nThree\nFour\nFive\nSix\n".match(/(?=[\s\S])(?:.*\n?){1,3}/g); 

demo

パターンの詳細を:

(?=[\s\S]) # ensure there's at least one character (avoid a last empty match) 

(?:.*\n?) # a line (note that the newline is optional to allow the last line) 

{1,3} # greedy quantifier between 1 and 3 
     # (useful if the number of lines isn't a multiple of 3) 

その他の方法:

"One\nTwo\nThree\nFour\nFive\nSix\n".split(/^/m).reduce((a, c, i) => { 
    i%3 ? a[a.length - 1] += c : a.push(c); 
    return a; 
}, []); 
1

ストレートフォワード:

(?:.+\n?){3} 

a demo on regex101.comを参照してください。内訳


、これは言う:

(?: # open non-capturing group 
.+ # the whole line 
\n? # a newline character, eventually but greedy 
){3} # repeat the group three times 
関連する問題