1

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!

0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ooh, I missed adding \w at the beginning. Thanks! I guess this is the solution I am looking for!
how to get an array of the result?
Press "Run code snippet" - the .match returns an array of all results
It works. I forgot adding g at the end to match all. Thanks! this is exactly what I am looking for.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.