String.split() by capital letters

How would I split a string by capital letters?
Example:

local mystring = "MyString"
mystring = string.split(mystring, --[[A capital letter string identifier]])
mystring = table.concat(mystring, " ")
>> "My String"

This would add a space between every capital letter in a string

I could use things like looping through each letter and using if letter = string.upper(letter) but i was hoping there was a simpler way like shown above

I’m not sure using the split method would be very useful.
You can loop through each character and check if string.upper(char) returns char, in which case it is an uppercase letter and you can add a space.

1 Like

Ok, I was hoping there might be a string.split identifier for them. Thanks!

string.upper(char) would return an uppercase character even if the input was a lowercase character. Never mind, you mean check the character against its uppercase variant. That would be fairly long-winded, especially when you can do the following instead.

local function splitTitleCaps(str)
	str = str:gsub("(%u)", " %1")
	return str:gsub("^%s", "")
	
end

local res = splitTitleCaps("MyString")
print(res) --My String
7 Likes

You can use this to check whether the character is an uppercase character.
If the method returns the character you gave it, you know it’s uppercase.

I figured that’s what you were trying to convey, that’d be a very unconventional solution, especially if the text was a paragraph.

There is a way to do this, using %u

image

Simply do:

string.split(mystring, "%u")

The split() method doesn’t support Lua’s search patterns.

local strings = "MyString"
local split = string.split(strings, "%u")
print(split[1], split[2]) --MyString, nil
1 Like