我正在尝试匹配包含关键字的段落。
示例文字:
I have a textfile containing text. Each paragraph
may span multiple lines.
Paragraphs have a newline between them. I would
like to match a paragraph that holds some text
and would like to match this line as well.
The regex doesn't have to match the first or last
paragraph (we can assume each paragraph has
newlines around it).
示例关键字:holds
(因此中间段应匹配)。
我尝试了以下正则表达式:var regX = /(.+\r?\n)+.*holds.*(?=(\r?\n)?)/igm;
这匹配前两行(不是最后一行):
Paragraphs have a newline between them. I would
like to match a paragraph that holds some text
将.*holds.*
更改为.*holds[\s\S]*
会选择太多(在示例中选择第2和第3段)(.*holds[\s\S]*?
也不起作用 - 不够贪婪。)
感谢您的帮助。
答案 0 :(得分:2)
你走了:
^\r?\n(?:.+\r?\n)*.*\bholds\b.*\r?\n(?:.+\r?\n)*(?=\r?\n)
与/gm
一起使用。 Demo
请注意,此regeix受catastrophic backtracking约束,但遗憾的是,您在JavaScript中无法做到这一点。
此模式基本上捕获一个空行,后跟一些行((?:.+\r?\n)*
),然后是包含holds
(.*\bholds\b.*\r?\n
)的行,然后再按0行或多行({ {1}}),最后确保最后一个换行符后跟换行符:(?:.+\r?\n)*
。