I think you mean "\\?", not "\?". The first backslash is substituted when the regsub line is evaluated, resulting in "?" being passed as a pattern to regsub, which will interpret the unescaped "?" as a quantifier - leading to the error message you got.
There is no way to invoke a command for each match using regsub - currently - some people in #tcl@freenode are experimenting with a new regexp engine that may be included in a future version of Tcl, but don't hold your breath
However... replacing a single character is easy to do using split,foreach and append:
Code: Select all
proc replacething {str find code} {
set out ""
foreach chr [split $str ""] {
append out [if {[string eq $chr $find]} {eval $code} {set chr}]
}
set out
}
# tclsh tests:
% proc rand i {expr {int(rand()*$i)}};# there's no [rand] in tclsh
% replacething "Hello????" ? {rand 9}
Hello5643
% replacething "axaxax" x {format %c [expr {65+int(rand()*26)}]}
aZaWaU