1
votes

I am trying to use regex with javascript, I have the following list:

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:

<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.

Simple code:

const reg = /[@\['](.)*['\]@]]/;
const arr = content.split(reg);

If anybody knows how to split it, I would appreciate sharing the solution. Thank you!

2

2 Answers

4
votes

Instead of split, consider .match, which may make the logic easier: either match word characters, or match @[, followed by any characters, followed by ]@:

\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:

\w+|@\[(?:(?:'[^']+'|"[^"]+")(?:, *|(?=\])))*\]@

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

1
votes

You may split the string using

s.split(/\s*(@\[.*?]@)\s*/).filter(Boolean)

See the JS demo:

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. The captured substrings land in the resulting array, and .filter(Boolean) removes empty items.