Search code examples
rubyregexspacealphanumeric

How do I match something that is not a letter or a number or a space?


I'm using Ruby 2.4. How do I match something that is not a letter or a number or a space? I tried

2.4.0 :004 > str = "-"
 => "-"
2.4.0 :005 > str =~ /[^[:alnum:]]*/
 => 0
2.4.0 :006 > str = " "
 => " "
2.4.0 :007 > str =~ /[^[:alnum:]]*/
 => 0

but as you can see it is still matching a space.


Solution

  • Your /[^[:alnum:]]*/ pattern matches 0 or more symbols other than alphanumeric chars. It will match whitespace.

    To match 1 or more chars other than alphanumeric and whitespace, you can use

    /[^[:alnum:][:space:]]+/
    

    Use the negated bracket expression with the relevant POSIX character classes inside.