2014-10-20 85 views
-1
每n行
"LINE 1. 
LINE 2. 
LINE 3. 
LINE 4. 
LINE 5. 
LINE 6." 

假設我想拆上面的字符串,每3線使用split()方法,我應該使用什麼樣的正則表達式分隔符來產生這樣的:將字符串分割使用正則表達式

["LINE 1. 
LINE 2. 
LINE 3.", 
"LINE 4. 
LINE 5. 
LINE 6."] 
+0

使用該示例??? /// – vks 2014-10-20 06:45:48

+1

怎麼樣的線7? – 2014-10-20 06:45:53

+3

分享你的研究可以幫助每個人。告訴我們你試過了什麼,以及它爲什麼不符合你的需求。這表明你已經花時間去嘗試幫助自己,它使我們避免重申明顯的答案,最重要的是它可以幫助你得到更具體和相關的答案!另請參閱[如何問](http://stackoverflow.com/questions/how-to-ask) – Cerbrus 2014-10-20 06:47:34

回答

0

第一,您不希望在此使用split(),因爲您需要一個正則表達式引擎,並且支持完整的lookaround assertion。幸運的是,.match()可以做到這一點一樣好(甚至可以說更好):

result = subject.match(/(?:^.*$\n?){1,3}/mg); 

測試它live on regex101.com

說明:

(?: # Start a non-capturing group that matches... 
^  # (from the start of a line) 
.* # any number of non-newline characters 
$  # (until the end of the line). 
\n? # Then it matches a newline character, if present. 
){1,3} # It repeats this three times. If there are less than three lines 
     # at the end of the string, it is content with matching two or one, as well. 
+0

工程就像一個魅力。我確信我可以使用'split()'與正則表達式,但我從來不知道'match()'可以在與標誌交匯處工作。 – painhurt 2014-10-20 07:13:35

相關問題