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
I think the example with 4 nested calls to replace
show the need for a variant replace(string, table)
!
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 !
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 |
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.
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.
[Please log in to post a comment]