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?
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With