为了使用Javascript和RegEx解析文本,我尝试将文本分割成几个较小的块。我在这里展示了我最好的一张照片,例子包括:
https://regex101.com/r/jfzTlr/1
我有一套规则要遵循:我想要收到块。每个块都以一个星号(*)作为第一个符号(如果没有缩进,否则是选项卡),后面跟着2-3个大写字母、逗号、(可能的)空格和一个代码,可以是A、R、T、RS或RSS。后面是一个可选的点。课后断线,文字来源。该文本在下一个星号出现的位置结束,遵循与上面相同的模式。
有谁能帮我找出相应的分割方法吗?到目前为止,这是我的模式:
[^\t](.{2,3}),\s?.{1,3}\.?\n.*非常感谢!
发布于 2018-01-19 13:55:07
既然您要使用JavaScript,那么为什么不使用一个为您提供要拆分的捕获字符串和分离的部分的拆分呢?然后将标题绑定到一个类似于
[[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);
发布于 2018-01-19 13:38:43
你可以用
^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?[\n\r](?:(?!^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?)[\s\S])+分成几个部分:
^[ \t]*\*[A-Z]{2,3} # start of the line, spaces or tabs and 2-3 UPPERCASE letters
,\s*(?:[ART]|RSS?)\.?[\n\r] # comma, space (optional), code, dot and newline
(?: # non-capturing group
(?!^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?)
# neg. lookahead with the same pattern as above
[\s\S] # \s + \S = effectively matching every character
)+这种技术被称为一种温和的贪婪的象征。
发布于 2018-01-19 13:49:47
希望这是你想要的。这个很管用。
([\*\t])+(.{2,3}),\s?.[A,R,T,RS,RSS]{1,3}\.?\n.*
https://stackoverflow.com/questions/48342162
复制相似问题