4

I'm building a command parser and I've successfully managed to split strings into separate words and get it all working, but the one thing I'm a bit stumped at is how to remove all punctuation from the string. Users will input characters like , . ! ? often, but with those characters there, it doesn't recognize the word, so any punctuation will need to be removed.

So far I've tested this:

func process_command(_input: String) -> String:
    var words:Array = _input.replace("?", "").to_lower().split(" ", false)

It works fine and successfully removes question marks, but I want it to remove all punctuation. Hoping this will be a simple thing to solve! I'm new to Godot so still learning how a lot of the stuff works in it.

Hidden
  • 63
  • 2

2 Answers2

3

You could remove an unwantes character by putting them in an array and then do what you already are doing:

var str_result = input
var unwanted_chars = [".",",",":","?" ] #and so on

for c in unwanted_chars:
   str_result = str_result.replace(c,"")

I am not sure what you want to achieve in the long run, but parsing strings can be easier with the use of regular expressions. So if you want to search strings for apecific patterns you should look into this: regex

Bugfish
  • 725
  • 5
  • 14
0

Given some input, which I'll just write here as example:

var input := "Hello, It's me!!"

We want to get a modified version where we have filtered the characters:

var output := ""

We need to know what we will filter. For example:

var deny_list := [",", "!"]

We could have a list of things we accept instead, you would just flip a conditional later on.

And then we can iterate over the string, for each character decide if we want to keep it, and if so add it to the output:

for position in input.length():
    var current_character := input[position]
    if not deny_list.has(current_character):
        output += current_character
Theraot
  • 31,890
  • 5
  • 57
  • 86