我如何写这个正则表达式以这样一种方式,它将捕获一个未知数量的行前缀? - How can i write this regex in such a way that it will capture an unknown amount of lines prefixed with?

- 此内容更新于:2015-12-20
主题:

如何将匹配所有以下行后最初的表达,有某种识别功能?例如说你:什么是正确的方法来得到一个匹配以下的地方:第一场比赛和第二匹配吗?以下是一个正确的方法吗?任何见解和建议是赞赏!

原文:

How would one go about matching all the following lines after a initial expression that has some sort of identifying feature?

For instance say you have the text:

The first line of text
! then another line of subtext
! then another....
! and so on..
The second line of text
! and so on..

What would be the correct approach to get a match where the following:

The first line of text
! then another line of subtext
! then another....
! and so on..

is the first match and

The second line of text
! and so on..

is the second match?

Would the following be a correct approach?

(.*)(\n!(?).*)*

Any insight and tips is appreciated!

网友:你应该添加regex101链接而不是添加截图,这是准备小提琴和将会帮助你得到解决方案

(原文:You should add the regex101 link instead of just adding screenshot, it is ready to fiddle and will help you to get the solution earlier)

网友:为什么不添加全球和多行标志?

(原文:Why not just add the global and multiline flags?)

解决方案:
DOTALL选项“打开”,匹配使用负面展望未来的开始下一个文本块:如在java:在perl中:在javascript中(不支持DOTALL旗):看到现场演示(捕获组添加到正则表达式用于匹配显示)崩溃:匹配线的开始不是匹配任何字符(包括换行与DOTALL)不紧随其后的是一个新的文本块的开始
原文:

With DOTALL option "on", match using a negative look ahead for the start of the next text block:

^[^!](.(?!^[^!]))*

eg in java:

"(?s)^[^!](.(?!^[^!]))*"

in perl:

/^[^!](.(?!^[^!]))*/s

in javascript (which doesn't support DOTALL flag):

/^[^!]([\s\S](?!^[^!]))*/

See live demo (capturing group added to regex only for match display purposes)

Breakdown:

  • ^[^!] matches the start of line that isn't a !
  • (.(?!^[^!])) matches any character (including newlines with DOTALL on) that are not followed by the start of a new text block
网友:演示,我添加了一个捕获组表明,这个答案是伟大的。+1。

(原文:Demo here, I added a capturing group to show that this answer works great. +1.)

解决方案:
使用这个(演示):说明:
原文:

Using this: The \w+ line of text((.|\n)(?!The \w+ line of text))+ (demo)

Explanation:

The \w+ line of text // match the first line of the segment
(
    (.|\n) // match anything, including newlines
    (?!The \w+ line of text) // not followed by a segment's first line
)+ // match this one or more times