这是输入字符串
Some content here
%% some text 1
Some content here 1
%% some text 2
Some content here 2
我想要这个
[
"Some content here\n\n",
"%% some text 1",
"\n\nSome content here 1\n\n",
"%% some text 2",
"\n\nSome content here 2\n\n"
]
或者这个
[
"Some content here\n\n",
"%% some text 1\n\nSome content here 1\n\n",
"%% some text 2\n\nSome content here 2\n\n"
]
输出中的括号只是表示匹配列表。
是否有一个多行正则表达式 (pcre) 可以让我实现这一目标?
谢谢
我用多行修饰符尝试了这个
(%% .+)
但显然它只匹配以 %%
开头的行。
应用这个表达式:
((?:(?!%%).)+.*(?:\n|$))?(%%.*)?
此正则表达式将每个部分捕获为一个组,包括分隔符 %%。为了从结果中排除定界符,我们可以只提取每个匹配项的第一组。
说明
((?:(?!%%).)+.*(?:\n|$))?
:这会捕获前面没有 %% 的任何字符,使用否定先行(?:(?!%%).)
.
的。匹配除换行符外的任何字符。
+ 匹配一次或多次出现。
.* 匹配任何字符直到行尾,并且 (?: |$) 匹配换行符或字符串结尾。
?使整个表达式可选,以便它匹配输入开头的空字符串。
(%%.*)?
:这会捕获 %% 定界符,后跟任何字符,直到行尾。
的。匹配除换行符以外的任何字符,* 匹配零次或多次出现。
?使整个表达式可选,以便它匹配输入末尾的空字符串。
为了便于理解,我在 Python 中进行了尝试。
import re
inputStr = "Some content here\n\n%% some text 1\n\nSome content here 1\n\n%% some text 2\n\nSome content here 2"
# each section must ends with a \n, or the end of the string
pattern = r'((?:(?!%%).)+.*(?:\n|$))?(%%.*)?'
parts = re.findall(pattern, inputStr)
# Extract the first group of each match
results = [part[0] for part in parts]
print(results)
re:split
与捕获组一起使用,因为捕获的部分也会返回:
re:split("content1\n\n%%text1\n\ncontent2","(%%.*)",[{return,list}]).
给出:
["content1\n\n", "%%text1", "\n\ncontent2"]