我在 Notepad++ 中写了数千行文本,其中多行以“FIRST_LINE”开头,后面跟着不同数量的行,最后以名为“LAST_LINE”的行结尾。虽然“FIRST_LINE”和“LAST_LINE”总是会出现,但中间行没有标准的开头,中间行数也没有固定。例如,有时中间有四行,如下所示,有时有两行,等等。
我需要一个搜索和替换公式来将“FIRST_LINE”、“LAST_LINE”以及其间的所有行合并为单独的文本行,以便:
FIRST_LINE,
second line lfutdytdyt
3rd line x;lkhr;lkj
fourth klufhkgfk
5th ;lkjk;lkj;lj
LAST_LINE,
FIRST_LINE,
lfutdytdyt
klkrjtlkj
LAST_LINE,
变成:
FIRST_LINE, second line lfutdytdyt, 3rd line x;lkhr;lkj, fourth klufhkgfk, 5th ;lkjk;lkj;lj, LAST_LINE,
FIRST_LINE, lfutdytdyt, klkrjtlkj, LAST_LINE,
(每行之间最好有一个逗号,但不是必须的):
提前感谢您的时间和帮助。
答案1
- Ctrl+H
- 找什么:
(?:((?:FIRST_LINE|LAST_LINE),\h*)|.+)\K\R+(?!FIRST_LINE,\h*)
- 用。。。来代替:
(?1:, )
- 查看 环绕
- 查看 正则表达式
- 取消选中
. matches newline
- Replace all
解释:
(?: # non capture group
( # group 1
(?: # non capture group
FIRST_LINE # literally
| # OR
LAST_LINE # literally
) # end group
, # a comma
\h* # 0 or more horizontal spaces
) # end group 1
| # OR
.+ # 1 or more any character but newline
) # end group
\K # forget all we have seen until this posiiton
\R+ # 1 or more any kind of linebreak (i.e. \r, \n, \r\n)
(?! # negative lookahead, make sure we haven't after:
FIRST_LINE, # literally
\h* # 0 or more horizontal spaces
) # end lookahead
替代品:
(?1 # if group 1 exists (there is FIRST_LINE or LAST_LINE)
# do nothing
: # else
, # add a comma
# and a space
) # endif
截图(之前):
截图(之后):