1. match_replace for every instance forever
- Posted by euphoric (admin) Nov 08, 2011
- 1292 views
I want to turn all multiple space sequences in a string to a single space. For example:
x = match_replace( " ","a b c d e f g h"," ") -- so x should be "a b c d e f g h"
I thought we had a match_count() function, but can't find anything like that in the manual. I figured I could loop
while match_count(" ",x) > 0 do x = match_replace( " ",x," ") end while
Or maybe match_replace() can be made to be recursive, but I don't see a flag for that. (In fact, the docs state "Replacements will not be made recursively on the part of haystack that was already changed." Maybe we could change that?)
Or... anybody know how to do this most quickly and efficiently?
2. Re: match_replace for every instance forever
- Posted by euphoric (admin) Nov 08, 2011
- 1291 views
Found match_all(), which I can get the length of... still... is there a better way?
3. Re: match_replace for every instance forever
- Posted by mattlewis (admin) Nov 08, 2011
- 1297 views
I want to turn all multiple space sequences in a string to a single space.
I'd do it with a slightly modified version of the std routine match_replace:
public function match_replace_all(object needle, sequence haystack, object replacement ) integer posn integer needle_len integer replacement_len integer scan_from integer cnt if max < 0 then return haystack end if cnt = length(haystack) if max != 0 then cnt = max end if if atom(needle) then needle = {needle} end if if atom(replacement) then replacement = {replacement} end if needle_len = length(needle) - 1 replacement_len = length(replacement) scan_from = 1 while posn with entry do haystack = replace(haystack, replacement, posn, posn + needle_len) cnt -= 1 if cnt = 0 then exit end if scan_from = posn + 1 -- <--- this is the change. Used to be "+ replacement_len" entry posn = match(needle, haystack, scan_from) end while return haystack end function
Matt
4. Re: match_replace for every instance forever
- Posted by mattlewis (admin) Nov 08, 2011
- 1291 views
I want to turn all multiple space sequences in a string to a single space.
I'd do it with a slightly modified version of the std routine match_replace:
Let me caveat that this will work for the scenario you're looking for, where the replacement is smaller than the needle. It will not work if you want to replace, say, "12" with "012".
You could also use regexes:
-- ck.ex include std/regex.e include std/console.e regex r = regex:new( " +" ) display( regex:find_replace( r, "a b c d e f g h"," ") )
$ eui ck.ex a b c d e f g h
Matt
5. Re: match_replace for every instance forever
- Posted by euphoric (admin) Nov 08, 2011
- 1290 views
You could also use regexes:
-- ck.ex include std/regex.e include std/console.e regex r = regex:new( " +" ) display( regex:find_replace( r, "a b c d e f g h"," ") )
$ eui ck.ex a b c d e f g h
Thanks, Matt! I really gotta learn regex...