So let's say I have a string called Hi there.
I am currently using
m:match("^(%S+)")
to get just Hi from the string, now all I need to do is just get "there" from the string but I have no idea how.
Checkout this page: http://lua-users.org/wiki/SplitJoin
There are numerous ways to split words in a string on whitespace.
This one seems like it might be a good fit for your problem:
function justWords(str)
local t = {} -- create an empty table
-- create a function to insert a word into the table
local function helper(word) table.insert(t, word) return "" end
-- grab each word in the string and pass it to `helper`
if not str:gsub("%w+", helper):find"%S" then return t end
end
table = justWords(example)
table[1] -- hi
table[2] -- there
table[3] -- nil
Related
Something like that is coming in:
str="Hello;this;is;a;text"
What I do want as result is this:
result="72:101:108:108:111;116:104:105:115;..."
which should be the Text in ASCII.
You could use string matching to get each word separated by ; and then convert, concat:
local str = "Hello;this;is;a;text"
for word in str:gmatch("[^;]+") do
ascii = table.pack(word:byte(1, -1))
local converted = table.concat(ascii, ":")
print(converted)
end
The output of the above code is:
72:101:108:108:111
116:104:105:115
105:115
97
116:101:120:116
I'll leave the rest of work to you. Hint: use table.concat.
Here is another approach, which exploits that fact that gsub accepts a table where it reads replacements:
T={}
for c=0,255 do
T[string.char(c)]=c..":"
end
T[";"]=";"
str="Hello;this;is;a;text"
result=str:gsub(".",T):gsub(":;",";")
print(result)
Another possibility:
function convert(s)
return (s:gsub('.',function (s)
if s == ';' then return s end
return s:byte()..':'
end)
:gsub(':;',';')
:gsub(':$',''))
end
print(convert 'Hello;this;is;a;text')
Finding certain character or string (such as ";") can be done by using string.find - https://www.lua.org/pil/20.1.html
Converting character to its ASCII code can be done by string.byte - https://www.lua.org/pil/20.html
What you need to do is build a new string using two functions mentioned above. If you need more string-based functions please visit official Lua site: https://www.lua.org/pil/contents.html
Okay...I got way further, but I can't find how to return a string made up of two seperate strings like
str=str1&" "&str2
I am new to lua and i am trying to extract the value form the right side of a splited string. I have this:
local t ={}
local data = ("ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run")
for word in string.gmatch(data, '([^,]+)') do
t[#t + 1] = word
end
local first = t[1]:gsub("%s+", "")
This gives me the string "ret=OK".
What can i do so that from this string to only get "OK", something like: get all from right of the equal sign and remove it and the left part. And this i must do for all the strings from "data" variable. Thank you.
I would recommend the following:
local data = 'ret=OK,type=aircon,reg=eu,dst=1,ver=2_2_5,pow=1,err=0,location=0,name=,icon=0,method=home only,port=30050,id=,pw=,lpw_flag=0,adp_kind=2,pv=0,cpv=0,led=1,en_setzone=1,mac=FCDBB382E70B,adp_mode=run'
local t = {}
for key, val in string.gmatch(data, '([^=,]*)=([^=,]*),?') do
t[key] = val
end
print(t['ret']) -- prints "OK"
print(t['adp_mode']) -- prints "run"
Note that the lua pattern makes the trailing comma optional (otherwise you miss the last keypair in the list).
Try this
for key, val in string.gmatch(data, "(%W*)=(%W*),") do
print(key.." equals "..val)
end
So this is a robust problem. I have a function which accepts 2 args (string_name, macros). Here it is so I can further explain.
function ParseStrings(string_name, macros)
return my_table[string_name]
-- All it does it returns the string_name's value
end
The problem is that the second arg is a table, and if it's a table then in the string there are going to be various parts that have the format "String stuff $MACRO_KEY; more string text" and the content between the $ and ; is the key to look up in the macro table sent with it. Now anytime a value like that appears in the string there will always be a second arg that's a table, so no problems their. I need to be able to count up the number of instances of macros in a string and then replace each macro component with it's respective macros' table value. So here's how the func is called in this instance...
local my_table = {
my_string = "My string content $MACRO_COMPONENT; more string stuff $MACRO_COMPONENT_SUB;$MACRO_COMPONENT_ALT;"
}
local macro = {
MACRO_COMPONENT = "F",
MACRO_COMPONENT_SUB = "Random Text",
MACRO_COMPONENT_ALT = "14598"
}
function ParseStrings(string_name, macros)
return my_table[string_name]
-- All it does it returns the string_name's value
end
ParseStrings("my_string", macro)
So I am thinking:
string.gsub(my_table[my_string]:match("%b$;"):sub(2,my_table[my_string]:match("%b$;"):len() - 1)
but this is a long and overtly complex answer (AFAIK) and from my tests it only does 1 replacement (because the pattern is only found once) and that's doesn't work well if there are multiple instances in the string. So ideas?
I'm trying to read a string in a specific format
RealSociedad
this is one example of string and what I want to extract is the name of the team.
I've tried something like this,
houseteam = sscanf(str, '%s');
but it does not work, why?
You can use regexprep like you did in your post above to do this for you. Even though your post says to use sscanf and from the comments in your post, you'd like to see this done using regexprep. You would have to do this using two nested regexprep calls, and you can retrieve the team name (i.e. RealSociedad) like so, given that str is in the format that you have provided:
str = 'RealSociedad';
houseteam = regexprep(regexprep(str, '^<a(.*)">', ''), '</a>$', '')
This looks very intimidating, but let's break this up. First, look at this statement:
regexprep(str, '^<a(.*)">', '')
How regexprep works is you specify the string you want to analyze, the pattern you are searching for, then what you want to replace this pattern with. The pattern we are looking for is:
^<a(.*)">
This says you are looking for patterns where the beginning of the string starts with a a<. After this, the (.*)"> is performing a greedy evaluation. This is saying that we want to find the longest sequence of characters until we reach the characters of ">. As such, what the regular expression will match is the following string:
<ahref="/teams/spain/real-sociedad-de-futbol/2028/">
We then replace this with a blank string. As such, the output of the first regexprep call will be this:
RealSociedad</a>
We want to get rid of the </a> string, and so we would make another regexprep call where we look for the </a> at the end of the string, then replace this with the blank string yet again. The pattern you are looking for is thus:
</a>$
The dollar sign ($) symbolizes that this pattern should appear at the end of the string. If we find such a pattern, we will replace it with the blank string. Therefore, what we get in the end is:
RealSociedad
Found a solution. So, %s stops when it finds a space.
str = regexprep(str, '<', ' <');
str = regexprep(str, '>', '> ');
houseteam = sscanf(str, '%*s %s %*s');
This will create a space between my desired string.
I searched but nothing explains how to do this,
for example
Dim sentence as String = "cat is an animal"
if i make a msgbox :
MsgBox(sentence)
it shows
cat is an animal
how to make a msgbox that says
cat
is
an
animal.
Easy way Replace space with new line
as in string words = MyString.Replace(" ","\r\n")
Split would be split on space in to an array , and then join that back up with new lines which is pointless unless you need the array for something else.