【问题标题】:Using regex to select AFTER one line all the way to a specific word on another line使用正则表达式在一行之后一直选择到另一行上的特定单词
【发布时间】:2018-11-20 00:31:55
【问题描述】:

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

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

【问题讨论】:

  • 您使用什么语言或应用程序?

标签: php regex wordpress


【解决方案1】:

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

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

输出:

Variable_1
Variable_2
Variable_3

对于 PHP,你可以试试下面的。

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

您可以查看此链接中的输出以了解您的示例。

Regex101 link

输出匹配:

National
South-East Asia
New South Wales
Victoria

【讨论】:

  • 很遗憾不能使用 Python。不过还是谢谢。
  • 你使用的是哪种语言?
  • 它在一个 wordpress 插件中,我假设它只是一般的 notepad++ 类型的查找和替换。
  • wordpress 是基于 php 的。所以你应该很好地使用 php 正则表达式函数。
  • 让我清楚你的问题,你需要选择没有任何_的单词,对吧?例如位置和部分
【解决方案2】:

使用 PHP 的解决方案是:

<?php

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

$initialValue = false;
$lastValue = false;
$arResult = [];
$arValue = explode("\n", $string);

foreach($arValue as $value) {
    $value = trim($value);
    if ($value == "Location") {
        $initialValue = true;
    } else if ($value == "Sections") {
        $lastValue = true;
    } else if ($initialValue == true && $lastValue == false) {
        $arResult[] = $value;
    }
}

echo implode(",",$arResult); // National,South-East Asia,New South Wales,Victoria

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 2010-09-13
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2023-03-19
    • 2021-06-03
    • 2016-09-28
    相关资源
    最近更新 更多