正则表达式 - 连接不以破折号开头的多行
Regexp - joining multiple lines not starting with dash
我有这样的行:
- test 1
test test test
test test test
test test test
- test2
- test3
test test t
test test test
- test 4
test test test
- test5
我正在寻找一个正则表达式来将它们转换成这样:
- test 1
test test test test test test test test test
- test2
- test3
test test t test test test
- test 4
test test test
- test5
即删除每行之后不以 \s*?\-
开头且不在以 \s*?\-
开头的行之前的所有新行
您可以在 Perl/PCRE/Java 等中使用此正则表达式:
搜索正则表达式:
(^-[^\n]*\n\h+|(?!^)\G)([^\n]*)\n(?!-)\h+
替换:
" "
正则表达式详细信息:
(^-[^\n]*\n\h+|(?!^)\G)
:第 1 组捕获以 -
开头的行,直到行尾字符后跟下一行的 1+ 个空格。 \G
断言位置在前一个匹配的末尾或第一个匹配的字符串的开头。
([^\n]*)
:匹配一行0个或更多non-newline个字符。在组 #2 中捕捉这个
\n(?!-)
: 如果后面没有-
则匹配换行符
\h+
: 匹配 1+ 个水平空格
怎么样
^(\h*[^-\s].*)\R(?!-)
并替换为</code></p>
<ul>
<li><a href="https://www.regular-expressions.info/anchors.html" rel="nofollow noreferrer"><code>^
匹配行开始
(\h*[^-\s].*)
首先是group captures: Any amount of h-space followed by a character, that is not-
或\s
白色space,后面是任意数量的任意字符
\R(?!-)
换行序列 not followed by 连字符
仅通过一个 space see this version 连接零件并替换为
(效率稍低)。
perl -ne 'if(/^-/){if($buffer){print" $buffer";print"\n"if/^-/}print;$buffer=""}else{chomp;$buffer.=s/^ +/ /r}END{print" $buffer\n"if$buffer}'
或者,更易读
perl -ne 'if (/^-/) {
if ($buffer) {
print " $buffer";
print "\n" if /^-/;
}
print;
$buffer = "";
} else {
chomp;
$buffer .= s/^ +/ /r;
}
END { print " $buffer\n" if $buffer }'
我有这样的行:
- test 1
test test test
test test test
test test test
- test2
- test3
test test t
test test test
- test 4
test test test
- test5
我正在寻找一个正则表达式来将它们转换成这样:
- test 1
test test test test test test test test test
- test2
- test3
test test t test test test
- test 4
test test test
- test5
即删除每行之后不以 \s*?\-
开头且不在以 \s*?\-
您可以在 Perl/PCRE/Java 等中使用此正则表达式:
搜索正则表达式:
(^-[^\n]*\n\h+|(?!^)\G)([^\n]*)\n(?!-)\h+
替换:
" "
正则表达式详细信息:
(^-[^\n]*\n\h+|(?!^)\G)
:第 1 组捕获以-
开头的行,直到行尾字符后跟下一行的 1+ 个空格。\G
断言位置在前一个匹配的末尾或第一个匹配的字符串的开头。([^\n]*)
:匹配一行0个或更多non-newline个字符。在组 #2 中捕捉这个
\n(?!-)
: 如果后面没有-
则匹配换行符
\h+
: 匹配 1+ 个水平空格
怎么样
^(\h*[^-\s].*)\R(?!-)
并替换为</code></p>
<ul>
<li><a href="https://www.regular-expressions.info/anchors.html" rel="nofollow noreferrer"><code>^
匹配行开始
(\h*[^-\s].*)
首先是group captures: Any amount of h-space followed by a character, that is not-
或\s
白色space,后面是任意数量的任意字符\R(?!-)
换行序列 not followed by 连字符 仅通过一个 space see this version 连接零件并替换为
(效率稍低)。
perl -ne 'if(/^-/){if($buffer){print" $buffer";print"\n"if/^-/}print;$buffer=""}else{chomp;$buffer.=s/^ +/ /r}END{print" $buffer\n"if$buffer}'
或者,更易读
perl -ne 'if (/^-/) {
if ($buffer) {
print " $buffer";
print "\n" if /^-/;
}
print;
$buffer = "";
} else {
chomp;
$buffer .= s/^ +/ /r;
}
END { print " $buffer\n" if $buffer }'