Since \E is the
only thing I found it messed up on, you could use a simple $iif():
alias countcs {
var %a = 2, %b
while $($ $+ %a,2) != $null {
inc %b $regex($1,[color:red]$iif($v1 == \E,/\\E/g,[/color]$+(/\Q,$v1,\E/g)[color:red])[/color])
inc %a
}
return %b
}
//echo -a * $countcs(a,\E) | echo -a * $countcs(\E,\E) | echo -a * $countcs(\E\E,\E)
* 0
* 1
* 2
Your bvar version, unfortunately, won't work:
//echo -a * $countcs($chr(12),$chr(1))
* 1
The reason for this is that it finds 1 ($chr(1)) in 12 ($chr(12)) because binary variables hold ascii numbers.
Edit:
heh, my $iif version will still mess up on things like $countcs(a\E,\E\E), i'll go for the messy but working code:
alias countcs {
var %i, %g = 2, %token, %n
while ($eval($+($,%g),2) != $null) {
%token = $v1
%i = 1
while ($mid($1,%i,$len(%token)) != $null) {
if ($v1 === %token) { inc %n }
inc %i
}
inc %g
}
return %n
}
Edit 2:
I just thought of a way to escape \E:
alias countcs {
var %a = 2, %b
while $($ $+ %a,2) != $null {
inc %b $regex($1,$+(/\Q,$replacecs($v1,\E,\E\\E\Q),\E/g))
inc %a
}
return %b
}
Edit 3: I changed $replace to $replacecs in the above code, it seems to work flawlessly now.