-2

I have a string in javascript like

"some text @[14cd3:+Seldum Kype] things are going good for @[7f8ef3:+Kerry Williams] so its ok"

From this i want to extract the name and id for the 2 people. so data like -

[ { id: 14cd3, name : Seldum Kype},
  { id: 7f8ef3, name : Kerry Williams} ]

how can u use regex to extract this?

please help

ghostCoder
  • 7,009
  • 8
  • 43
  • 63

3 Answers3

2

var text = "some text @[14cd3:+Seldum Kype] things are going " +
           "good for @[7f8ef3:+Kerry Williams] so its ok"

var data = text.match(/@\[.+?\]/g).map(function(m) {
    var match = m.substring(2, m.length - 1).split(':+');
    return {id: match[0], name: match[1]};
})
// => [ { id: '14cd3', name: 'Seldum Kype' },
//    { id: '7f8ef3', name: 'Kerry Williams' } ]

// For demo
document.getElementById('output').innerText = JSON.stringify(data);
<pre id="output"></pre>
falsetru
  • 314,667
  • 49
  • 610
  • 551
1

Get the id from Group index 1 and name from group index 2.

@\[([a-z\d]+):\+([^\[\]]+)\]

DEMO

Explanation:

  • @ Matches a literal @ symbol.
  • \[ Matches a literal [ symbol.
  • ([a-z\d]+) Captures one or more chars lowercase alphabets or digits.
  • :\+ Matches :+ literally.
  • ([^\[\]]+) Captures any character but not of [ or ] one or more times.
  • \] A literal ] symbol.
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
1

Try the following, the key is to properly escape reserved special symbols:

@\[([\d\w]+):\+([\s\w]+)\]
Peter Pei Guo
  • 7,536
  • 17
  • 32
  • 51