Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# trim null chars

Tags:

null

f#

I have a string recieved from a web socket:

let websocket = new ClientWebSocket()
let source = new CancellationTokenSource()
let buffer = ArraySegment(Array.zeroCreate 32)  

do! websocket.ConnectAsync(url, source.Token) 
do! websocket.ReceiveAsync(buffer, source.Token) 

let str = Encoding.ASCII.GetString buffer.Array

let trim1 = Regex.replace str "\0" String.Empty  // result is empty string
let trim2 = Regex.replace str "\\0" String.Empty // result is empty string
let trim3 = str.TrimEnd [| '\\'; '0' |]          // result is untouched

I am obviously trying to trim the excess null chars

In the debugger the value for str is "{\"type\":\"hello\"}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"

When printed it looks like: {"type":"hello"} which makes sense, the symbols are being interpreted properly.

I seem to not be able to do this simple task in f#, what am I doing wrong?

like image 915
Grayden Hormes Avatar asked Mar 24 '17 17:03

Grayden Hormes


1 Answers

Using ASCII escaping will do the trick:

let trim3 = str.TrimEnd [| '\x00' |]

You could also escape it with the unicode escape sequence:

let trim3 = str.TrimEnd [| '\u0000' |]  

Your regular expression version does not work because the proper way to represent a null character in a regular expression is by ASCII escaping using "\x00", or unicode escaping using "\u0000".

like image 151
Chad Gilbert Avatar answered Nov 02 '22 23:11

Chad Gilbert