Replace function in macro code: Weird behaviour?


Hi all,

Just wanted to share what I experienced this morning.
I have a macro using “replace” function to transform this
"19759 scan1.scan"
in this
"19759 scan1"
Here is the piece of code:

SCANlist = SortFileList(“dir”, pa, “”, “.scan”); // get the list of .scan files

prefix = replace(SCANlist[0], “.scan”, “”);

When I run it with IJ v1.51q or r (java 1.8 64 bits, Windows 7), result for prefix variable is “197591”!
From what I understand, it means that for some weird reason, it replaces not only
".scan" occurences, but " scan" as well!
I am interested in getting some ideas about that general behaviour.

Important note: I know that you can use other ways to get the correct result… So nothing to worry about debugging this macro…



Good day!

The commented list of macro commands tells us:

replace(string, old, new)
Returns the new string that results from replacing all occurrences of old in string with new, where old and new are single character strings. If old or new are longer than one character, each substring of string that matches the regular expression old is replaced with new. When doing a simple string replacement, and old contains regular expression metacharacters (’.’, ‘[’, ‘]’, ‘^’, ‘$’, etc.), you must escape them with a “\”. For example, to replace “[xx]” with “yy”, use string=replace(string,"\[xx\]",“yy”). See also: matches.

Important, not weird:

replacing all occurrences of old in string with new




Maybe this is what you’re after:

fileName = "19759 scan1.scan";
fileName = substring( fileName, 0, indexOf( fileName, ".scan" ) );
print( fileName );


fileName = "19759 scan1.scan";
fileName = replace( fileName, "\\.scan", "" );
print( fileName );




Hi Herbie,

You’re absolutely right, simple commands need some more attention sometimes.
I didn’t expect that escape was needed for the dot…
Thanks for getting me back to the basics!