简体   繁体   中英

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?

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

You can do this using lookahead .See demo.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM