[英]Split string with specific formation Angular 6, Typescript
I am trying to use regex with javascript, I have the following list: 我正在尝试将正则表达式与javascript一起使用,我有以下列表:
word1 @['id1', 'name1']@ @['id2', 'name2']@ @['id3', 'name3']@ word2 @['id4', 'name4']@ word3 @['id5', 'name5']@ word1 @ ['id1','name1'] @ @ ['id2','name2'] @ @ ['id3','name3'] @ word2 @ ['id4','name4'] @ word3 @ [' id5','name5'] @
I want to detect everything has: @[' ..... ']@ and split them like that: 我想检测所有内容:@ ['.....'] @并像这样拆分它们:
word1
@['id1', 'name1']@
@['id2', 'name2']@
@['id3', 'name3']@
word2
@['id4', 'name4']@
word3
@['id5', 'name5']@
So I can read the id and the name later to be able to create a link: 因此,我以后可以阅读ID和名称,以便创建链接:
<a href="url/[id]">[name]</a>
I have tried this regex: 我已经尝试过此正则表达式:
[@\['](.)*['\]@]
But it is just mark everything from the first @[' till the end at name5. 但这只是在第一个@ ['到名称5的末尾标记所有内容。
Simple code: 简单的代码:
const reg = /[@\['](.)*['\]@]]/;
const arr = content.split(reg);
If anybody knows how to split it, I would appreciate sharing the solution. 如果有人知道如何拆分它,我将不胜感激分享解决方案。 Thank you! 谢谢!
Instead of split
, consider .match
, which may make the logic easier: either match word characters, or match @[
, followed by any characters, followed by ]@
: 可以考虑使用.match
而不是split
,这可以使逻辑更容易:匹配单词字符,或者匹配@[
,然后匹配任何字符,再匹配]@
:
\w+|@\[.*?\]@
const input = `word1 @['id1', 'name1']@ @['id2', 'name2']@ @['id3', 'name3']@ word2 @['id4', 'name4']@ word3 @['id5', 'name5']@`; console.log(input.match(/\\w+|@\\[.*?\\]@/g));
If the inside of the []
may contain ]@
s you don't want to match, such as @['id1', ']@', 'name1']@
, then you'll need a bit more logic - inside the []
s, repeat groups of '
or "
delimited strings: 如果的内部[]
可能包含]@
是你不想匹配的,如@['id1', ']@', 'name1']@
,那么你就需要更多的逻辑-内[]
,重复以'
或"
分隔的字符串组:
\w+|@\[(?:(?:'[^']+'|"[^"]+")(?:, *|(?=\])))*\]@
https://regex101.com/r/rDW2iD/1 https://regex101.com/r/rDW2iD/1
You may split the string using 您可以使用
s.split(/\s*(@\[.*?]@)\s*/).filter(Boolean)
See the JS demo: 参见JS演示:
var s = "word1 @['id1', 'name1']@ @['id2', 'name2']@ @['id3', 'name3']@ word2 @['id4', 'name4']@ word3 @['id5', 'name5']@"; console.log(s.split(/\\s*(@\\[.*?]@)\\s*/).filter(Boolean));
The pattern matches 0+ whitespaces, then captures @[
, any 0+ chars other than line break chars, as few as possible, up to the first ]@
, and then matches without capturing 0+ whitespaces. 该模式匹配0+个空格,然后捕获@[
,除换行符以外的任何0+个字符,并尽可能少地捕获,直到第一个]@
,然后匹配而不捕获0+个空格。 The captured substrings land in the resulting array, and .filter(Boolean)
removes empty items. 捕获的子字符串落在结果数组中, .filter(Boolean)
删除空项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.