This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
joshmanisdabomb's profile picture

Remove Characters From A String That Are Not Spaces Or Alphanumerics.

Started by joshmanisdabomb, 12 November 2013 - 11:18 AM
joshmanisdabomb #1
Posted 12 November 2013 - 12:18 PM
Patterns have always confused me in Lua. They're probably the most confusing thing in there for me.

I'm making a username system, and I want the usernames to only be able to contain alphanumerics or spaces. I could find on Google how to remove either non-alphanumeric and non-spaces, but not both.
I also want leading spaces and trailing spaces to disappear, much like how this site describes it. However, I used the examples it provided and it just didn't work and I have no idea why.

So, if anyone would kindly help me out, it would be nice. Thanks.
Edited on 12 November 2013 - 11:20 AM
TheOddByte #2
Posted 12 November 2013 - 12:47 PM
Well please post your current code and post what is not working on that site?
Here's a site that explains patterns as well as string.gsub
joshmanisdabomb #3
Posted 12 November 2013 - 12:57 PM
Well please post your current code and post what is not working on that site?
Here's a site that explains patterns as well as string.gsub

I've looked at that site tons and tons of times, including just now, and I still don't get it.
This didn't work for space trimming:
str:gsub("^%s*(.-)%s*$", "")
This doesn't work for removing unneeded characters:
str:gsub('^%W*(.-)%S*','')
LBPHacker #4
Posted 12 November 2013 - 01:12 PM
Did you try actually assigning str to the result of :gsub?
str = str:gsub(whatever, another)
joshmanisdabomb #5
Posted 12 November 2013 - 01:23 PM
Did you try actually assigning str to the result of :gsub?
str = str:gsub(whatever, another)

Yes.
LBPHacker #6
Posted 12 November 2013 - 01:52 PM
Well, the pattern you've shown us for trimming spaces works for me. As for removing anything not alphanumerical and non-space (and I assume you mean only the actual space character by that):
str = str:gsub("[^%w ]", "")
Edited on 12 November 2013 - 12:52 PM
joshmanisdabomb #7
Posted 12 November 2013 - 01:59 PM
Well, the pattern you've shown us for trimming spaces works for me. As for removing anything not alphanumerical and non-space (and I assume you mean only the actual space character by that):
str = str:gsub("[^%w ]", "")
Thank you, this worked.

Edit: Trimming spaces now works too. Thank you.
Edited on 12 November 2013 - 01:00 PM