2013-09-10 33 views
3

在任何编程语言中,我都知道如何有效地限制给定文件或字符串中的行数,这在这里不是问题。然而,在这种情况下,我期待通过正则表达式来做到这一点。在这种模式下,我仅使用\n换行符。我不需要别人,比如\r回车用正则表达式限制文本中的行数

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

上述正则表达式解释说:

(?:  group, but do not capture (between 0 and 3 times)- 
(?:  group, but do not capture (optional) 
    \n  '\n' (newline) 
)?  end of grouping 
[^\n]* any character except: '\n' (newline) (0 or more times) 
){0,3} end of grouping 

现在使用的字符串正则表达式,如..

In this line is foo bar and baz 
In this line is bar and foo 
In this line is baz and bar 
In this line we have foo 
In this line we have bar and foo and baz 
In this line we have foobar 
In this line we have foo 
In this line we have foo and bar 
In this line we have bar and baz and foo 

这将返回没有问题,行1-3

在上述串,行78,和9所有包含单词foo所有的本身无论是在开始时,中间或字符串的末尾。

现在我的问题是我怎么能实现一个前瞻或后面来搜索一个字符串,并找到3连续的文本行,它们都有相同的关键字foo本身,而不是一个单词的前缀或用另一个词结合?所以它只会匹配7-9而不是1-6

回答

4

我不明白为什么这需要任何种类的lookaround。只是比赛只包含foo行:

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

注意,使用可选的\n这还不如匹配的是包含foo三次线。为了避免这种情况,使用

(?:(?:^|\n)[^\n]*foo[^\n]*){3} 
// or 
(?:[^\n]*foo[^\n]*(?:\n|$)){3} 

(取决于你的正则表达式的味道,你可以使用不同的anchors字符串开始/结束)


如果您需要foo站在它自己的,只需添加word boundaries它:

(?:\n?[^\n]*\bfoo\b[^\n]*){3} 
+0

查看上面更新的问题。 – hwnd

+0

现在我明白了我需要解决的问题,这让我很头疼。 – hwnd