Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match words with condition

I have a string like this

var msg = "ATEAM-3121 ATEAM-31 123 ATEAM-32 #finish \n ATEAM-3211 \n ATEAM-51 ATEAM-52 ATEAM-53 12345677 #finish ATEAM-1000";

In above string, for each line, I would like to match tags matching ATEAM-[0-9]* before #finish tag. If any line does not have #finish, all ATEAM tags should be ignored.

Here is the non regex solution that works

msg = msg.split("\n");
var tickets = [];
msg.forEach(function(val) {
  var ticks = val.split(' ');
  for(var i = ticks.indexOf('#finish'); i >= 0; i-- ) {
    if(ticks[i].match(/^ATEAM-.*$/)) {
      tickets.push(ticks[i]);
    }
  }
});
console.log(tickets);

But would like to convert it to Regex solution and this is what I have tried

msg.match(/(ATEAM-[0-9]*|\#finish)/g);

But it gives me result like in this fiddle, but its not as expected. Can anyone help me on this?

like image 407
Exception Avatar asked Sep 26 '22 23:09

Exception


1 Answers

ATEAM-[0-9]+(?=.*?#finish)

You can do this using lookahead.See demo.

https://regex101.com/r/uF4oY4/88

like image 86
vks Avatar answered Nov 15 '22 04:11

vks