Finding null character using Regex in Perl

20,832

Solution 1

You can use \x followed by the hex code of an ASCII character to match that ASCII character.

E.g. /\x3F/ will match a "?", /\x46\x4F\x4F/ to match "FOO".

See it here on Regexr

So /\x00/ would match the NULL character.

Solution 2

you can use \0 to find null character. (but do not follow this with another digit)

Share:
20,832

Related videos on Youtube

Somnath Paul
Author by

Somnath Paul

Updated on April 19, 2020

Comments

  • Somnath Paul
    Somnath Paul about 4 years

    I want to find the null characters in an array, which I have. I tried displaying the ASCII value and it printed 0 (So I am confirmed it is a null value). How do I write a regex to filter out those values.

    I wrote :

    m/^$/ig 
    

    which really didn't help me. Does anybody know how to match a null character ?

    • Somnath Paul
      Somnath Paul about 11 years
      Is there any method to write ASCII value in regex to match it ?
    • TLP
      TLP about 11 years
      use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper $yourvariable will show you exactly what the hidden character is.
    • Somnath Paul
      Somnath Paul about 11 years
      $VAR1 = ""; I got this diaplay @TLP
    • TLP
      TLP about 11 years
      That means the variable is empty then, no null character there. It should match /^$/. It should also be considered "false" in a boolean check, such as if ($var). You can also check $var !~ /./s, meaning it fails a check for any character. It depends on your situation what the best way to check it is.
    • Somnath Paul
      Somnath Paul about 11 years
      I used $var !~ /./s, and I got the desired output. Thank you very much TLP :)
    • Somnath Paul
      Somnath Paul about 11 years
      Also there are some elements like [] What does these means by Dumper ? @TLP
    • TLP
      TLP about 11 years
      If you mean $VAR = [] that is an empty array. Such that you would get if you did print Dumper \@array, where @array = ().
    • TLP
      TLP about 11 years
      The Data::Dumper module is one of the best debugging tools, right after use strict; use warnings;. Learn to use it, and you will have an invaluable tool at your side.
  • Somnath Paul
    Somnath Paul about 11 years
    It really didn't help me out :(
  • Raheel Hasan
    Raheel Hasan about 11 years
    did you try it in regex? like /\0/ims
  • Raheel Hasan
    Raheel Hasan about 11 years
    maybe its not a null char, its an invisible whitespace. try this in that case /\p{Z}/
  • Somnath Paul
    Somnath Paul about 11 years
    I tried display using "ord", which displayed as 0. Can we still say it is not a null character ?
  • Somnath Paul
    Somnath Paul about 11 years
    Well I said it was a ASCII value 0 , not a hex value.
  • ChaseTheSun
    ChaseTheSun about 11 years
    hex 0x30 == ascii 0. Can you try printing the mystery char out as a hex string?