-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
  • 484,719
  • 26
  • 302
  • 397
blacktone
  • 144
  • 9
  • 1
    Use `^(\S+)\s+(.*?)(?:\s+())?$`, 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 ', 'COMMAND', 'Some Thing With Spaces In String ', undefined, index: 0, input: 'COMMAND Some Thing With Spaces In String ', groups: undefined ]``` I ran the string with `.match(/^(\S+)\s+(.*?)(?:\s+())?$/);`. 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

0

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
  • 1,955
  • 2
  • 7
  • 16
  • So I tried this with `let args = message.content.substring(PREFIX.length).match(/^(\w+) (.+?)(?: |$)()?$/);` and got the portion inside the 2nd group. Basically reading "Some Thing With Spaces In The Name " 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 – blacktone May 29 '20 at 00:53