Removing all Text in a string after a underscore

Let’s say I have this string "Cabin_5123456" and I want to remove the underscore and everything after it so it turns into "Cabin"

my best guess is to search for the _ with string.match then use string.sub to remove the text but I’m not quite sure how to put that into code

I searched for a while and found posts with similar situations but I don’t quite understand how to do it the way I need it to be done

any help is appreciated

1 Like

You can look at string pattern captures in the page for string patterns.

A proposed solution would be text:match('^(.-)_'); breaking this down, we know with ^ we match from the start of the string, () means we have a capture which will be returned as a separate variable, and .- will match the least amount of any character it can until it reaches the _ after it. Note that since the _ is not included in the capture, it won’t be returned or anything after it.

You could use it as such.

local cabin_text = my_text:match('^(.-)_')
3 Likes

I’d use string.find, but it’s the same thing you mentioned. If you use string.find(“_”), you can find the index of where the _ is, then take string.sub(string, 1, index-1) to get everything before it.

Only thing is it won’t support names with _ inside them (eg. Cabin_One_5123456). In that case, you’d need to use string patterns like @AMD_chan mentioned.

string.find is exactly what I needed to make it work, I skipped over it and thought I should use match

I’d like to note there’s also a new string.split API which can be used for this:

string.split("Cabin_1234", "_") --> { "Cabin", "1234" }
string.split("Cozy_Cabin_1234", "_") --> { "Cozy", "Cabin", "1234" }

string.split("Cabin_1234", "_")[1] --> "Cabin"
26 Likes

Hello! I have been using this, it helped me out a lot. I was wondering how I could do this for all the words after a space instead?

print(string.split(“/warn User Stop spamming chat please”, " ")[2])

How could I make it print “Stop spamming chat please”? Thanks. Hope to hear back soon!

If you want to stick with using string.split you can concatenate all the strings after the second one.

local split_result = string.split("/warn User Stop spamming chat please", " ")
-- concatenate strings after the second one in the list with space
print(table.concat(split_result, " ", 3))
1 Like