Monday 28 March 2011

Attack of ^M aka carriadge return (CR) in vbscript

I spent a lot of time nailing an obscure vbscript problem. I was using a function to split a command output using vbscript regular expression object. the bizarre problem I encountered was that because the command output was many lines long it contained vbcrlf characters as the last 2 chr of the line.

before splitting the string into the ObjRE.Submatches collection the whole string appeared as you would expect
xxxx vbcrlf
yyyyy vbcrlf
...

post splitting using a pattern and the 'multiline' property I ended up with each submatch collection object having a hidden cr charater last character which in vi appears as ^M. in my other text editor (editplus) it said it was chr 0A

I tried everything I could think of to replace or even 'instr' the chr using various possiblites (chr 10, chr 13, vbcrlf) etc. but vbscript just ignores it and the cr remains annoyingly embedded in the string just itching to cause trouble later on...

eventually the only fix I could find was to trim the last char from each submatch item e.g
  For Each submatch In oMatch.Submatches
   if len(submatch)=0 or isnull(submatch) then
  else
      retstr = retstr & Left(submatch,Len(submatch)-1) 

this seems a dumb way to do this but vbscript just won't seem to handle the single cr character consistently.

No comments:

Post a Comment