Vimal
Vimal

Reputation: 2857

How to match a specific string with regular expression?

I have a string

var txt="[!Qtextara1] Description1 [@Qtextara1]
        [!Qtextarea2] Description2 [@Qtextarea2]"

I want to match this string using regular expression The output should something like this.

{Qtextara1: Description1,  Qtextarea2: Description2} 

Is it possible with regular expression? Please help me..
Thanks in advance.

Upvotes: 1

Views: 86

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use the following regex:

\[\!([\s\S]+?)\]\s+([\s\S]+?)\s*\[@\1\]

Explanation:

  • \[\! - Match literal [!
  • ([\s\S]+?) - Capture group 1 to match 1 or more characters inside [] (the tag name, we'll need that later on)
  • \]\s+ - Literal ] and 1 or more whitespace symbols
  • ([\s\S]+?) - Capture group 2 to capture (even multiline) description
  • \s*\[@\1\] - Match 0 or more whitespace, followed by a literal [@, then a backreference to the first capture group (the tag name), and then a literal ].

See demo.

var re = /\[\!([\s\S]+?)\]\s+([\s\S]+?)\s*\[@\1\]/g; 
var test_str = '[!Qtextara1] Long Description Wi[th%^&*\n(Abra# $]Cadabra~!~## 1 [@Qtextara1]\n        [!Qtextarea2] Description2 [@Qtextarea2]';
 
while ((m = re.exec(test_str)) !== null) {
    alert(m[1] + ", " + m[2])
}

Upvotes: 4

romuleald
romuleald

Reputation: 1434

I got this

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/);

That split in 3 part:

Part 1:

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[1];
"[!Qtextara1]"

Part 2:

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[2];
"Description1"

Part 3:

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[3];
"[@Qtextara1]"

But that could be greatly improved.

Upvotes: 0

Related Questions