在多行上捕获相同的正则表达式

时间:2017-07-24 18:48:09

标签: regex pcre

我想要捕获新行中列出的一系列文件名,我已经想出如何在第一行中捕获文件名,但我还没想出如何在后续行中重复它线。

# Input
# data/raw/file1
# data/raw/file2

# Output
# data/interim/file1
# data/interim/file2

当前尝试

我目前的正则表达式是

# Input\n(# (.*))

我的内部捕获组正确捕获data/raw/file1

所需输出

我想要的是获取# Input# Output之间的所有文件,因此在此示例中,data/raw/file1data/raw/file2

2 个答案:

答案 0 :(得分:2)

使用\G魔法:

(?:^#\s+Input|\G(?!\A))\R*(?!#\s+Output)#\s*(.*)|[\s\S]*

Live demo

正则表达式分解

(?:                 # Start of non-capturing group (a)
    ^#\s+Input          # Match a line beginning with `# Input`
    |                   # Or
    \G(?!\A)            # Continue from previous successful match point
)                   # End of NCG (a)
\R*                 # Match any kind of newline characters
(?!#\s+Output)      # Which are not followed by such a line `# Output`
#\s*(.*)            # Start matching a path line and capture path
|                   # If previous patterns didn't match....
[\s\S]*             # Then match everything else up to end to not involve engine a lot

PHP代码:

$re = '~(?:^#\s+Input|\G(?!\A))\R*(?!#\s+Output)#\s*(.*)|[\s\S]*~m';
$str = '# Input
# data/raw/file1
# data/raw/file2

# Output
# data/interim/file1
# data/interim/file2';

preg_match_all($re, $str, $matches, PREG_PATTERN_ORDER, 0);

// Print the entire match result
print_r(array_filter($matches[1]));

输出:

Array
(
    [0] => data/raw/file1
    [1] => data/raw/file2
)

答案 1 :(得分:2)

使用s修饰符,preg_matchpreg_split,您可以自行获得每个结果。

preg_match('/# Input\n(# (?:.*?))# Output/s', '# Input
# data/raw/file1
# data/raw/file2

# Output
# data/interim/file1
# data/interim/file2', $match);
$matched = preg_split('/# /', $match[1], -1, PREG_SPLIT_NO_EMPTY);
print_r($matched);

演示:https://3v4l.org/dAcRp

正则表达式演示:https://regex101.com/r/5tfJGM/1/