0

I have a string which contains the data in xml format like as

str = "<p><a>_a_10gd_</a><a>_a_xy8a_</a><a>_a_1020_</a><a>_a_dfa7_</a><a>_a_ABCD_</a></p>";

What I am trying to do is that I want to capture _abc__(Value)__ from all possible mach. I have tried it that way

Let say I am doing this in JavaScript :-

var regex = /_a_(.+)_/g ;
var str = "<a>_a_10gd_</a><a>_a_xy8a_</a><a>_a_1020_</a><a>_a_dfa7_</a><a>_a_ABCD_</a>";

while(m = regex.exec(str)){
     console.log(m[1]); // m[1] should contains each mach 
}

I want to get all maching group in an array like this :-

var a = ['10gd', 'xy8a', '1020', 'dfa7', 'ABCD'];

Please tell me that what will be required regex and explain it also because I am new to regex and their capturing group.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
Deepak Dixit
  • 1,510
  • 15
  • 24

2 Answers2

1

Just change (.+) to (.+?) see:

var regex = /_a_(.+?)_/g ;
var str = "<a>_a_10gd_</a><a>_a_xy8a_</a><a>_a_1020_</a><a>_a_dfa7_</a><a>_a_ABCD_</a>";

while(m = regex.exec(str)){
     console.log(m[1]); // m[1] should contains each mach 
}

for more information about greediness, see What do lazy and greedy mean in the context of regular expressions?

Community
  • 1
  • 1
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • Thanks for your answer , can you explain me how ? is working in regex here because as I know ? is used for optional thing – Deepak Dixit Apr 26 '17 at 12:52
0

Another option is to accept only characters except _ before the _ (instead of . which you have used), like so:

var regex = /_a_([^_]+)_/g ;
Vasan
  • 4,810
  • 4
  • 20
  • 39