Log In  

Cart #knutil_replace-1 | 2023-07-27 | Code ▽ | Embed ▽ | No License
6

Feature Overview

REPLACE() Replaces the specified string with the specified string.

  • The first argument string replaces all matches to the second argument string with the third argument string.
  • After the fourth and fifth words, you can further specify the search match and the words to be replaced.
  • This function consumes 58 Token.
--"str" becomes "string for replace".
str = replace('[test] for replace', '[test]', 'string') 

This function is included in the KNUTIL library.

release note


v0.2

  • multiple substitutions can be made with a single function call.

v0.1

  • first release

P#60157 2022-08-15 08:06 ( Edited 2023-07-27 14:36)

1

I think the example with 4 nested calls to replace show the need for a variant replace(string, table)!

P#115797 2022-08-15 17:03
1

That's a pretty decent replace there, @shiftalow. I was seeing if I can make the code smaller with split() - I don't think I can.

You get the medal on this one. Gold star !

P#115804 2022-08-15 18:16

@merwok

Yes, we do. Some projects may require more than one replacement at a time.
We can consider the following multi-replacement versions if needed.

-- table argment version
function replace(s,t)
 local a,i=s
  for f,r in pairs(t) do
   s,a,i=a,'',1
   while i<=#s do
    if sub(s,i,i+#f-1)~=f then
     a..=sub(s,i,i)
     i+=1
    else
     a..=r or ''
     i+=#f
    end
   end
  end
 return a
end

local str="you got a banana."
      .."you found an apple."
      .."you ate an orange."

str=replace(str
 ,{
  banana="\fa[bananaノ\vtノ]\f6"
  ,apple="\f8[apple●\vvイ]\f6"
  ,orange="\f9[orangeう\vz𝘭]\f6"
  ,["."]=".\n"
 }
)

?str
-- tuple argments version
function replace(s,f,r,...)
 local a,i='',1
 while i<=#s do
  if sub(s,i,i+#f-1)~=f then
   a..=sub(s,i,i)
   i+=1
  else
   a..=r or ''
   i+=#f
  end
 end
 return ... and replace(a,...) or a
end

local str="you got a banana."
      .."you found an apple."
      .."you ate an orange."

str=replace(str
 ,"banana","\fa[bananaノ\vtノ]\f6"
 ,"apple","\f8[apple●\vvイ]\f6"
 ,"orange","\f9[orangeう\vz𝘭]\f6"
 ,".",".\n"
)

?str
P#115874 2022-08-16 16:24 ( Edited 2022-08-16 16:25)

@dw817

Thanks for the Gold star!

I too believe that if replace() using split() could be built up, it would suppress Token considerably.
But, hmmm. I recall the problem of not being able to split on delimiters of more than 2 characters.

https://www.lexaloffle.com/bbs/?tid=46617

P#115876 2022-08-16 16:24

I updated to REPLACE() ver 0.2!!

  • multiple substitutions can be made with a single function call.

I thought that perhaps multiple substitutions would be used more frequently.

P#132459 2023-07-27 14:39 ( Edited 2023-07-27 14:47)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 09:28:18 | 0.040s | Q:21