Search code examples
rubyregexnullterminate

What could be the regex for null terminated ASCII string?


I am reading one file using Ruby and I am able to filter out strings stored in fixed sized formats. But I want to filter variable size string which is left by me in the end using some regex or some other thing.

Right now I am scanning string with following line

s.scan(/(.{4})(.{4})(.{4})(.{4})(.{4})(.{4})(.{4})(.{4})(.{4})(.*)/).each do |f,g,h,i,j,k,l,m,n,p| 

but still want to filter this (. *) part of string by separating null terminated strings from it. How can I do this?


Solution

  • I don't really understand why your regex is the way it is, but \0 is a null byte used in the regex (or \x00 if you prefer hex codes). Basically:

    "foo\x00bar".split(?\x00)
    => ["foo", "bar"]
    
    "foo\x00bar" =~ /\0/
    => 3