Lua gsub second instance - lua

I'm using
local mystring = 'Thats a really nice house.'
string.gsub(mystring,"% ", "/",1)
to replace the first white space character with an slash.
But how to replace only the second occurrence of the white space?

You can use a function as replacement value in string.gsub and count the matches yourself:
local mystring = "Thats a really nice house."
local cnt = 0
print( string.gsub( mystring, " ", function( m )
cnt = cnt + 1
if cnt == 2 then
return "/"
end
end ) )

Try string.gsub(mystring,"(.- .-) ", "%1/",1).

You can replace the first instance with something else (assuming the replacement is not present in the string itself, which you can check), then replace it back:
print(mystring:gsub("% ", "\1",1):gsub("% ", "/",1):gsub("\1","% ", 1))
This prints: Thats a/really nice house.. Also, you don't need to escape spaces with %.

Related

Replace last comma on string Lua

I have this string
Apples, Oranges, Grapes
How can i replace last comma for and?
Havent learn enough of patterns but i've tried several ways such as
str:gsub(",$", "and", 1)
Isnt supposed that magic character $ reads string from end --> begin?
My problem becomes because im concatenating an array using table.concat
Your table:
local t = {"Apples", "Oranges", "Grapes"}
Method #1:
Concatenate the last item using "and":
local s = #t > 1
and table.concat(t, ", ", 1, #t-1).." and "..t[#t]
or table.concat(t, ", ")
print(s) --> Apples, Oranges and Grapes
Method #2:
Replace the last comma:
local s = table.concat(t, ", ")
s = s:gsub("(.*),", "%1 and")
print(s) --> Apples, Oranges and Grapes
local str = "Apples, Oranges, Grapes"
print(str:gsub(",(%s+%w+)$", " and%1"))

how to get numbers from string in LUA?

I have string "0,0,0,-58.43083113,,"
and how could I get all the 4 numbers as double with LUA? Thanks!
I have tried with string.match(). But it didn't work.
local text = "0,0,0,-58.43083113,,"
local numbers = {}
text:gsub("[^,]+", function (str) table.insert(numbers, tonumber(str)+.0) end)
print(table.concat(numbers, ", "))
or
for str in text:gmatch("[^,]+") do
table.insert(numbers, tonumber(str) + .0)
end
Of course this assumes that you only have number representations and commas in your string.

Trying to make function which takes string as input and returns no. of words in whole string

**It takes Input as a string such as this - 'Nice one'
And Output gives - 4,3 (which is no. Of words in sentence or string)
**
function countx(str)
local count = {}
for i = 1, string.len(str) do
s = ''
while (i<=string.len(str) and string.sub(str, i, i) ~= ' ' ) do
s = s .. string.sub(str, i, i)
i = i+1
end
if (string.len(s)>0) then
table.insert(count,string.len(s))
end
end
return table.concat(count, ',')
end
You can find a simple alternative with your new requirements:
function CountWordLength (String)
local Results = { }
local Continue = true
local Position = 1
local SpacePosition
while Continue do
SpacePosition = string.find(String, " ", Position)
if SpacePosition then
Results[#Results + 1] = SpacePosition - Position
Position = SpacePosition + 1
-- if needed to print the string
-- local SubString = String:sub(Position, SpacePosition)
-- print(SubString)
else
Continue = false
end
end
Results[#Results + 1] = #String - Position + 1
return Results
end
Results = CountWordLength('I am a boy')
for Index, Value in ipairs(Results) do
print(Value)
end
Which gives the following results:
1
2
1
3
def countLenWords(s):
s=s.split(" ")
s=map(len,s)
s=map(str,s)
s=list(s)
return s
The above functions returns a list containing number of characters in each word
s=s.split(" ") splits string with delimiter " " (space)
s=map(len,s) maps the words into length of the words in int
s=map(str,s) maps the values into string
s=list(s) converts map object to list
Short version of above function (all in one line)
def countLenWords(s):
return list(map(str,map(len,s.split(" "))))
-- Localise for performance.
local insert = table.insert
local text = 'I am a poor boy straight. I do not need sympathy'
local function word_lengths (text)
local lengths = {}
for word in text:gmatch '[%l%u]+' do
insert (lengths, word:len())
end
return lengths
end
print ('{' .. table.concat (word_lengths (text), ', ') .. '}')
gmatch returns an iterator over matches of a pattern in a string.
[%l%u]+ is a Lua regular expression (see http://lua-users.org/wiki/PatternsTutorial) matching at least one lowercase or uppercase letter:
[] is a character class: a set of characters. It matches anything inside brackets, e.g. [ab] will match both a and b,
%l is any lowercase Latin letter,
%u is any uppercase Latin letter,
+ means one or more repeats.
Therefore, text:gmatch '[%l%u]+' will return an iterator that will produce words, consisting of Latin letters, one by one, until text is over. This iterator is used in generic for (see https://www.lua.org/pil/4.3.5.html); and on any iteration word will contain a full match of the regular expression.

How to replace spaces between words with another word?

I have a cell G which stores random words like "Hello, How are you"
I want to replace all the spaces with %20 to make it
"Hello%20,%20How%20%are%20you"
How can i replace spaces with %20?
Thanks
try like this:
=SUBSTITUTE(G1; " "; "%20")
Select the cells you wish to change and run this:
Sub SpaceChanger()
Dim rng As Range, r As Range
Set rng = Intersect(Selection, ActiveSheet.UsedRange)
For Each r In rng
If r.Value <> "" Then
If InStr(r.Value, " ") <> 0 Then
r.Value = Replace(r.Value, " ", "%20")
End If
End If
Next r
End Sub
(using a macro will allow you to change the values "in place")

Lua need to split at comma

I've googled and I'm just not getting it. Seems like such a simple function, but of course Lua doesn't have it.
In Python I would do
string = "cat,dog"
one, two = string.split(",")
and then I would have two variables, one = cat. two = dog
How do I do this in Lua!?
Try this
str = 'cat,dog'
for word in string.gmatch(str, '([^,]+)') do
print(word)
end
'[^,]' means "everything but the comma, the + sign means "one or more characters". The parenthesis create a capture (not really needed in this case).
If you can use libraries, the answer is (as often in Lua) to use Penlight.
If Penlight is too heavy for you and you just want to split a string with a single comma like in your example, you can do something like this:
string = "cat,dog"
one, two = string:match("([^,]+),([^,]+)")
Add this split function on the top of your page:
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
local theStart = 1
local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
while theSplitStart do
table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
end
table.insert( outResults, string.sub( self, theStart ) )
return outResults
end
Then do as follows:
local myString = "Flintstone, Fred, 101 Rockledge, Bedrock, 98775, 555-555-1212"
local myTable = myString:split(", ")
for i = 1, #myTable do
print( myTable[i] ) -- This will give your needed output
end
For more information, visit : Tutorial: Lua String Magic
Keep Coding...............:)
-- like C strtok, splits on one more delimiter characters (finds every string not containing any of the delimiters)
function split(source, delimiters)
local elements = {}
local pattern = '([^'..delimiters..']+)'
string.gsub(source, pattern, function(value) elements[#elements + 1] = value; end);
return elements
end
-- example: var elements = split("bye# bye, miss$ american# pie", ",#$# ")
-- returns "bye" "bye" "miss" "american" "pie"
To also handle optional white space you can do:
str = "cat,dog,mouse, horse"
for word in str:gmatch('[^,%s]+') do
print(word)
end
Output will be:
cat
dog
mouse
horse
This is how I do that on mediawiki:
str = "cat,dog"
local result = mw.text.split(str,"%s*,%s*")
-- result[0] will give "cat", result[1] will give "dog"
actually, if you don't care spaces, you can use:
str = "cat,dog"
local result = mw.text.split(str,",")
-- result[0] will give "cat", result[1] will give "dog"
The API used here is implemented in Scribunto MediaWiki extension. Here is the split() method reference documentation and here is the source code for that. It relies on a lot of other capabilities in Scribunto's Lua common libraries, so it will only work for you if you are actually using MediaWiki or plan to import most of the Scribunto common library.
Functions like string.split() are largely unnecessary in Lua since you can
express string operations in LPEG.
If you still need a dedicated function a convenient approach is
to define a splitter factory (mk_splitter() in below snippet)
from which you can then derive custom splitters.
local lpeg = require "lpeg"
local lpegmatch = lpeg.match
local P, C = lpeg.P, lpeg.C
local mk_splitter = function (pat)
if not pat then
return
end
pat = P (pat)
local nopat = 1 - pat
local splitter = (pat + C (nopat^1))^0
return function (str)
return lpegmatch (splitter, str)
end
end
The advantage of using LPEG is that the function accepts
both valid Lua strings and patterns as argument.
Here is how you would use it to create a function that
splits strings at the , character:
commasplitter = mk_splitter ","
print (commasplitter [[foo, bar, baz, xyzzy,]])
print (commasplitter [[a,b,c,d,e,f,g,h]])

Resources