Home > database >  Trying to match multiple of a word in one string
Trying to match multiple of a word in one string

Time:10-12

I have a command for a bot I work on that's as follows :

.command @user @user2 (user list can grow etc..) item

The current regex I am using is

/([.command]  [@A-Za-z0-9_?]  [A-Za-z0-9] )/g

The problem I have is that I need it to find each user instead of only the first occurrence. Ideally I'd also like to be able to target that each user starts with a "@" character.

Any help on this appreciated.

CodePudding user response:

Use

/^\.([a-z] )\s ((?:@[\w?]\s ) )(\w )/i

Capture group 1 is the command.

Capture group 2 will contain all the @user parameters, you can use .split(/\s /) to split it into separate users.

Capture group 3 is the item at the end

CodePudding user response:

This is one (of many) solution:

function getUsers(command){

   var result = [];

   var index = command.indexOf("@");
   while(index>-1){
      var i1 = command.indexOf("@", index);
      var i2 = command.indexOf(" ", i1);
      if(i2==-1){i2 = command.length;}
      var user = command.substr(i1, i2-i1);
      index = command.indexOf("@", i2);
      result.push(user);
   }

   return result;

}

getUsers("cmd @a1 @a2 @a3 ckkasd @a5 a6 @a7")

This one dont uses regular expressions. It will consume less memory and will run faster for big strings.

  • Related