1

I have a string pattern like

var str = "@#[test][some desc]@#@#[test1][some desc for test2]@#"

I need to extract string between the chars (first @# and @# and again [ and ]) using regex.

I have tried below regex

/@#(.+?)@#/g

which gives me the result @#[test][some desc]@# and @#[test1][some desc for test2]@#

Here I wanted to exclude the @# also.

Help me to write a regex which gives me the result in an array.

The variable array which will have 2 elements and each element will have only

test
some desc

test1
some desc for test2

Pls help with the regex in typescript.

2
  • Whoever came up with this godawful format should be forced to solve your problem. Commented Jan 31, 2020 at 5:13
  • Please check my answer: I use a single regex to parse the strings in your format. Commented Feb 1, 2020 at 15:46

2 Answers 2

1

You may use

/@#\[([^\]]*)]\[([^\]]*)]@#/g

See the regex demo

Details

  • @#\[ - @#[ substring
  • ([^\]]*) - Group 1: any 0+ chars other than]`
  • ]\[ - ][ substring
  • ([^\]]*) - Group 2: any 0+ chars other than ]
  • ]@# - a ]@# substring.

JS demo:

var regex = /@#\[([^\]]*)]\[([^\]]*)]@#/g;
var s = "@#[test][some desc]@#@#[test1][some desc for test2]@#";
var m, res = [];
while (m = regex.exec(s)) {
  res.push([m[1], m[2]]);
}
console.log(res);

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

Comments

0

I don't know typescript but I think is similar to JS:

var str = "@#[test][some desc]@#@#[test1][some desc for test2]@#";

var a = str.match(/@#([^@#]+)@#/g);
for(var i=0; i<a.length; i++)
{
    var d = a[i].match(/\[([^\]]+)\]\[([^\]]+)\]/);
    console.log(d[1], d[2]);
}

output:

test some desc
test1 some desc for test2

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.