2014-10-20 87 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

相关问题