Search code examples
luapattern-matchinggsublua-patterns

LUA string, drop non alphanumeric or space


I have customer input that may include letters, digits or spaces. For instance:

local customer_input = 'I need 2 tomatoes';

or

local customer_input = 'I need two tomatoes';

However, due to the nature of my application, I may get #, *, @, etc, in the customer_input string. I want to remove any non alphanumeric characters but the space.

I tried with these:

customer_input , _ = customer_input:gsub("%W%S+", ""); 

This one drops everything but the first word in the phrase.

or

customer_input , _ = customer_input:gsub("%W%S", ""); 

This one actually drops the space and the first letter of each word.

So, I know I am doing it wrong but I am not really sure how to match alphanumeric + space. I am sure this must be simple but I have not been able to figure it out.

Thanks very much for any help!


Solution

  • You may use

    customer_input , _ = customer_input:gsub("[^%w%s]+", ""); 
    

    See the Lua demo online

    Pattern details

    • [^ - start of a negated character class that matches any char but:
      • %w - an alphanumeric
      • %s - a whitespace
    • ]+ - 1 or more times.