How would I get the first letter before a space in a string?

I am trying to create a script that can get the character that comes before a space in string. So far I have string.match("1 2 3", "%a "), but I do not know how to get only the first character that comes before the space instead of every character. Help greatly appreciated, thank you!

2 Likes

try
string.match("1 2 3", "%w ")

then trim the spacebar at the end

That returns the last character of the string.

1 Like

image

It should not based on the example you gave. What is the string you are using?

1 Like

just do

string.gsub('a b c', ' .*', ''):sub(-1)

but replace the ‘a b c’ with your string

2 Likes

I want the script to print 1, 2, and 3. To explain myself better if the string was “Test 123 Testing” I would want the script to return “t3g”

1 Like

that doesn’t make sense, why would it print a capital T and if you want that to be printed then should 1 also be printed?

1 Like

I edited my previous post to say g. I made a typo.

A bit confused on what the goal is but I believe this code might be what your looking for

local str = "hello world, blah blah" 
for i,v in str:split(" ") do 
	print(string.sub(v, -1)) 
end

--> o
--> ,
--> h
--> h

if you want to remove special characters like , you could do this instead

local str = "hello world, blah blah" 
local args = str:split(" ")
for i,v in args do 
	v = v:gsub("%W", "")
	print(v:sub(-1))
end

--> o
--> d
--> h
--> h
1 Like

Oops, I need the script to get the first letter of the word.
So: “Test String for fun” becomes “TSff” (not tgrn)

replace the sub(-1) with sub(1, 1)

1 Like

Adding to the existing solution, it can be slightly shortened into a single pattern:

--[[
    %S matches any non-whitespace char
    * matches zero or more of the preceeding class
    
    non-space followed by zero or more non-whitespaces
]]
for c in string.gmatch(str, "(%S)%S*") do
    print(c)
end

--[[
    Substitution instead
    %s* matches zero or more whitespaces
    %1 refers to the capture
    
    non-space followed by zero or more non-spaces
    followed by zero or more spaces
]]
local subStr = string.gsub(str, "(%S)%S*%s*", "%1")

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.