-1

I'm building a bot that will take commands through Discord Channels like "!COMMAND Some Thing With Spaces In The Name <@123412341234>"

I need a regex expression that, while using javascript, will allow me to get the following:

const args = ["COMMAND", "Some Thing With Spaces In The Name", "<@123412341234>"];

OR, in the absence of the user mention at the end:

const args = ["COMMAND", "Some Thing With Spaces In The Name"];

I've tried using (\S+)\s(.+)(\s<@\d+>)? but what I get looks like:

const args = ["COMMAND", "Some Thing With Spaces In The Name <@123412341234>"];

I need the mention separate. What I'm most interested in is the COMMAND and the argument after it without the mention. Which could be in the command or not. I know I can get the mention by doing message.mentions.users.first(). That's not really what I'm after.

Any help would be greatly appreciated. Thank you.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
blacktone
  • 144
  • 1
  • 11
  • 1
    Use `^(\S+)\s+(.*?)(?:\s+(<@\d+>))?$`, see [demo](https://regex101.com/r/V3Rhwm/1). – Wiktor Stribiżew May 28 '20 at 23:25
  • Thank you @WiktorStribiżew for your response. I tried it, and here's what I got: ```[ 'COMMAND Some Thing With Spaces In String <@!478745025275101185>', 'COMMAND', 'Some Thing With Spaces In String <@!478745025275101185>', undefined, index: 0, input: 'COMMAND Some Thing With Spaces In String <@!478745025275101185>', groups: undefined ]``` I ran the string with `.match(/^(\S+)\s+(.*?)(?:\s+(<@\d+>))?$/);`. The mention still shows up on the third one and the fourth item is undefined. – blacktone May 28 '20 at 23:36
  • 1
    So, my regex also works, right? – Wiktor Stribiżew May 29 '20 at 10:03
  • Yes, it also worked. Thank you. I was missing the !. – blacktone May 30 '20 at 11:22

1 Answers1

1

You could use capturing groups, and then reference the capturing groups when constructing your strings.

Regex:

^!(\w+) (.+?)(?: |$)(<@\d+>)?$
  • Capturing group 1 is "COMMAND"
  • Capturing group 2 is "Some Thing With Spaces In The Name"
  • Capturing group 3 is "<@123412341234>" only if it is present, otherwise capturing group 3 is undefined
Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25
  • So I tried this with `let args = message.content.substring(PREFIX.length).match(/^(\w+) (.+?)(?: |$)(<@\d+>)?$/);` and got the <@123412341234> portion inside the 2nd group. Basically reading "Some Thing With Spaces In The Name <@123412341234>" with the last group (3) undefined. – blacktone May 29 '20 at 00:08
  • Nevermind. This is the solution I was looking for. The discord mention starts with <@!, not <@. Once I added the missing exclamation it all worked perfectly. Thank you! – blacktone May 29 '20 at 00:53