[Omake] String manipulation
Jason Hickey
jyh at cs.caltech.edu
Tue Aug 7 14:07:04 PDT 2007
Oops, the subst function I sent earlier has a mistake--the
replacement wasn't being evaluated. Here is an updated version.
Input string is: ABCx123x456xDEFx555x666x
Output string is: ABCy456y123yDEFy666y555y
Jason
#
# Replace all occurrences of $(from) with $(to)
# in the string $s, returning the result as a string.
# The $(to) should be a function of one argument.
#
# In $(to), $0 stands for the entire match, and $i stands
# for the i'th match part\(...\).
#
subst(from, to, s) =
# Create a channel from a string
inx = $(open-in-string $s)
# Perform the substitution collecting results
result[] =
lex-search($(inx))
case $(from)
# Evaluate the replacement in this context
result[] += $(string $(to))
export
default
result[] += $0
export
# Remember to close the input
close($(inx))
# Flatten into a normal string
concat($(EMPTY), $(result))
# Example
in = ABCx123x456xDEFx555x666x
out = $(subst $'x\([0-9]+\)x\([0-9]+\)x', $(fun y$2y$1y), $(in))
println($"Input string is: $(in)")
println($"Output string is: $(out)")
--
Jason Hickey http://www.cs.caltech.edu/~jyh
Caltech Computer Science Tel: 626-395-6568 FAX: 626-792-4257
More information about the Omake
mailing list