我尝试使用 Javascript 和 RegEx 将文本分成几个较小的 block 以便对其进行解析。我在这里展示了我最好的镜头,示例包括:
https://regex101.com/r/jfzTlr/1
我有一套规则要遵循:我想接收区 block 。每个 block 都以星号 (*) 作为第一个符号(如果没有缩进,则为制表符),然后是 2-3 个大写字母、一个逗号、一个(可能的)空格和一个可以是 A、R、T 的代码、RS 或 RSS。后面是一个可选的点。之后换行,文本出现的地方。该文本在下一个星号出现的地方结束,遵循与上面相同的模式。
有人可以帮我弄清楚如何相应地拆分它吗?到目前为止,这是我的模式:
[^\t](.{2,3}),\s?.{1,3}\.?\n.*
非常感谢!
最佳答案
既然您要使用 JavaScript,为什么不使用 split 来实现它,它可以为您提供要拆分的捕获字符串以及分离的部分?然后将标题绑定(bind)到一个数组中,看起来像
[[heading1, block1], [heading2, block2], ...]
这样一来,您就可以立即获得格式良好的数据,以便进行后续处理。只是一个想法!
const s = `*GW, A
This is my very first line. The asterics defines a new block, followed by the initials (2-3 chars), a comma, a (possible) space and a code that could be A, R, T, RS or RSS. Followed by that is an optional dot. Linebreak afterwards, where the text comes.
*JP, R.
New block here, as the line (kind of) starts with an asterics. Indentations with 4 spaces or a tab means that it is a second level thing only, that does not need to be stripped away necessarily.
But as you can see, a block can be devided into several
lines,
even with multiple lines.
*GML, T.
And so we continue...
Let's just make sure that a line can start with an
*asterics, without breaking the whole thing.
*GW, RS
Yet another block here.
*GW, RSS.
And a very final one.
Spread over several lines.
*TA, RS.
First level all of a sudden again.
*PA, RSX
Just a line to check whether RSX is a separate block.
`;
const splits = s.split(/\*([A-Z]{2,3}),\s?([AT]|RS{0,2})(\.?)\n/).slice(1);
const grouped = [];
for (let i = 0; i < splits.length; i += 4) {
const group = splits.slice(i, i+3);
group[3] = splits[i+3].trim().split(/\s*[\r\n]+\s*/g);
grouped.push(group);
}
console.log(grouped);
关于javascript - 将文本拆分为 block (Javascript、正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342162/