Search code examples
schemeracketwhitespace

Check if a string is empty or only whitespace characters in racket


How do I check if a string is empty or all whitespace characters in racket? the example on their site (string$?) doesn't work


Solution

  • Use regexp-match-exact? with this regex: #px"\\s*", which matches whitespace character zero or more times:

    > (regexp-match-exact? #px"\\s*" "a")
    #f
    > (regexp-match-exact? #px"\\s*" "")
    #t
    > (regexp-match-exact? #px"\\s*" "    ")
    #t
    > (regexp-match-exact? #px"\\s*" "
    ")
    #t
    

    non-empty-string? has different results for empty string and string with whitespace characters:

    > (non-empty-string? "  ")
    #t
    > (non-empty-string? "")
    #f