首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将文本分割成块(Javascript,regex)

将文本分割成块(Javascript,regex)
EN

Stack Overflow用户
提问于 2018-01-19 13:24:35
回答 3查看 146关注 0票数 4

为了使用Javascript和RegEx解析文本,我尝试将文本分割成几个较小的块。我在这里展示了我最好的一张照片,例子包括:

https://regex101.com/r/jfzTlr/1

我有一套规则要遵循:我想要收到块。每个块都以一个星号(*)作为第一个符号(如果没有缩进,否则是选项卡),后面跟着2-3个大写字母、逗号、(可能的)空格和一个代码,可以是A、R、T、RS或RSS。后面是一个可选的点。课后断线,文字来源。该文本在下一个星号出现的位置结束,遵循与上面相同的模式。

有谁能帮我找出相应的分割方法吗?到目前为止,这是我的模式:

代码语言:javascript
运行
复制
[^\t](.{2,3}),\s?.{1,3}\.?\n.*

非常感谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-01-19 13:55:07

既然您要使用JavaScript,那么为什么不使用一个为您提供要拆分的捕获字符串和分离的部分的拆分呢?然后将标题绑定到一个类似于

代码语言:javascript
运行
复制
[[heading1, block1], [heading2, block2], ...]

这样,您可以立即以一种很好的格式处理数据。只是个主意!

代码语言:javascript
运行
复制
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);

票数 1
EN

Stack Overflow用户

发布于 2018-01-19 13:38:43

你可以用

代码语言:javascript
运行
复制
^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?[\n\r](?:(?!^[ \t]*\*[A-Z]{2,3},\s*(?:[ART]|RSS?)\.?)[\s\S])+

a demo on regex101.com

分成几个部分:

代码语言:javascript
运行
复制
^[ \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
)+

这种技术被称为一种温和的贪婪的象征。

票数 1
EN

Stack Overflow用户

发布于 2018-01-19 13:49:47

希望这是你想要的。这个很管用。

([\*\t])+(.{2,3}),\s?.[A,R,T,RS,RSS]{1,3}\.?\n.*

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48342162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档