-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
  • 1
  • 9
  • 49
  • 72

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
  • 357,413
  • 63
  • 732
  • 636
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
  • 172,303
  • 28
  • 230
  • 274
1

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

@\[([\d\w]+):\+([\s\w]+)\]
Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54