Skip to main content

Parse Text

Code snippet to parse text into a slice of arguments, much like how .CmdArgs is constructed.

Licensed under the terms of the Unlicense.

Code

{{/*
Parses text into a slice of arguments, much like how .CmdArgs is constructed.
See <https://yagpdb-cc.github.io/code-snippets/parse-text> for more information.

Licensed under the terms of the Unlicense.
Author: jo3-l <https://github.com/jo3-l>
*/}}

{{/* Let $text be the text. */}}
{{ $text := .StrippedMsg }}

{{ $regex := `\x60(.*?)\x60|"(.*?)"|[^\s]+` }}
{{ $clean := cslice }}
{{ range reFindAllSubmatches $regex $text }}
{{- $clean = $clean.Append (or (index . 2) (index . 1) (index . 0)) -}}
{{ end }}

Usage

First, add in the code snippet above:

{{/* code snippet goes here */}}

Next, change the value of $text to the value you like. Say we wanted to use .Message.Content rather than .StrippedMsg:

{{/* Let $text be the text. */}}
- {{ $text := .StrippedMsg }}
+ {{ $text := .Message.Content }}
{{/* rest of code snippet goes here */}}

You may now access the parsed slice of arguments using $clean, which will be a cslice.

{{/* code snippet goes here */}}
Parsed args: `{{json $clean}}`
tip

You can convert $clean to a string slice (what .CmdArgs, .Args, and so on are) by using the StringSlice method: {{$clean.StringSlice}}.

Author

This code snippet was written by @jo3-l.