在随后的后续行上传播匹配

时间:2012-01-22 18:05:31

标签: regex

请考虑此示例:

header-1
    item1-1
    item1-2
    item1-3
header-2
    item2-1
    item2-2
...

我想要这种格式:

header-1 item1-1
header-1 item1-2
header-1 item1-3
header-2 item2-1
header-2 item2-2
...

我想使用正则表达式可以轻松实现这一点,但我无法弄清楚

欢迎任何正则表达式语法,我在Wine下使用RegexBuddy

1 个答案:

答案 0 :(得分:2)

使用RegexBuddy,您可以分两步完成。

首先搜索(?<=(^\S.*$)(?s:.*?))^\s+并将所有内容替换为\1<space>

这会给你

header-1
header-1 item1-1
header-1 item1-2
header-1 item1-3
header-2
header-2 item2-1
header-2 item2-2

<强>解释

(?<=   # Make sure we're right after the following match:
 (     # Match and capture in group 1 (the header):
  ^    # From the start of the line...
  \S   # but only if the first character is not whitespace
  .*   # match any number of characters except newlines
  $    # until the end of the line (OK, that's redundant).
 )     # End of group 1
 (?s:  # Start a non-capturing group, DOTALL mode enabled
  .*?  # that matches any number of any character, as few as possible.
 )     # End of group
)      # End of lookbehind assertion
^\s+   # Now match one or more whitespace characters at the start of the line

然后搜索^(.*)$\r?\n(?=\1)并替换为空字符串。

这导致

header-1 item1-1
header-1 item1-2
header-1 item1-3
header-2 item2-1
header-2 item2-2

<强>解释

^       # Match from the start of the line
(.*)    # Match and capture the entire line in group 1
$       # Match until the end of the line (OK, redundant again)
\r?\n   # Match a linebreak
(?=\1)  # Do all this only if the next line starts with the same string as above