首页 > 解决方案 > 使用正则表达式在一行之后一直选择到另一行上的特定单词

问题描述

我不确定这是否可能。我有一个新行上包含特定单词的列表,我需要选择这些行之间的单词。例如我的来源是:

Word_1
Word_2
Location
Variable_1
Variable_2
Variable_3
Section
Word_9

我需要正则表达式来查找 Location 之后的行,我正在使用(.*(?<=\bLocation\s)(\w+).*)|.*并替换为$1. 但是,这只给了我 Variable_1 ,我需要它给我Variable_1,Variable_2,Variable_3. 这就是问题所在,有时只有一个变量,有时是 2,有时是 3,有时是 4。但是,下面的单词将始终是 Section。所以我想我基本上需要一些方法来告诉 Regex 在 Location 之后但在 Section 之前选择每一行。

有任何想法吗?

现实世界的例子:

Category
Business
Dates
StatusOpen
Closing Information
Location
National
South-East Asia
New South Wales
Victoria
Sections
General
Difficulty Rating
Administrator

输出将是National,South-East Asia,New South Wales,Victoria

标签: phpregexwordpress

解决方案


在 Python 中,您可以在您的 re.DOTALL 中使用 DOTALL。

print(re.findall("Location(.*)Section",string,re.DOTALL)[0])

输出:

Variable_1
Variable_2
Variable_3

对于 PHP,您可以尝试以下方法。

'\w*Location(.*)Section/s'

您可以检查此链接中的输出以获取您的示例。

正则表达式 101 链接

输出匹配:

National
South-East Asia
New South Wales
Victoria

推荐阅读