Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I exclude Spaces of a string and whilst leave the Characters?

Asked by
Ziffixture 6913 Moderation Voter Community Moderator
5 years ago

I’m using String:match() to preform that task preferred. Yet it only returns the first word, the format I’m using is String:match('[%a%p]+'). Could anyone help me figure out how to gather the rest of the sentence?

String = "  Hello $&@    World  !"
print(String:match('[%a%p]+'))

--// -> “Hello”

Thanks!

I also believe this would end out returning HelloWorld! is there a way I could or at least one Space between words?

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

The apparent problem


The problem here is that you are looking for all letters %a and all punctuation symbols %p, but it stops when it reaches a whitespace, which is %s.

so your code just outputs

Hello

An easy situation would be where the characters that aren't needed are before or after all of the wanted text.

That is where gmatch comes in.

Gmatch


the string.gmatch function is a pretty useful one, as it is an iterator. That meaning i can do this:

local str = "Hi My Name Is Bob"

for word in string:gmatch(%a+) do
    print(word) --Hi, My, Name, Is, Bob
end

For your purpose, you can simple get the word by doing

String = "  Hello $&@    World  !"

for word in String:gmatch("%a+") do
      print(word)
end

or

String = "  Hello $&@    World  !"

for word in String:gmatch("[%p%s]+") do
      print(word)
end

And then you can simply add them to a table and concatenate them

String = "  Hello $&@    World  !"
local words = {}

for word in String:gmatch("[^%a]+") do
      table.insert(words,word)
end

print(table.concat(words," "))--"Hello World"

However, the exclamation point can't be used as $,&, and @ are also considered punctuation characters, which means you could also be included :/

Reference links:

gmatch

patterns and "magic characters"

Hopefully this helped you out :3

Ad

Answer this question