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
。
在上述串,行7
,8
,和9
所有包含单词foo
所有的本身无论是在开始时,中间或字符串的末尾。
现在我的问题是我怎么能实现一个前瞻或后面来搜索一个字符串,并找到3
连续的文本行,它们都有相同的关键字foo
本身,而不是一个单词的前缀或用另一个词结合?所以它只会匹配7-9
而不是1-6
。
查看上面更新的问题。 – hwnd
现在我明白了我需要解决的问题,这让我很头疼。 – hwnd