I can't seem to figure out the regex pattern for matching strings only if it doesn't contain whitespace. For example
"this has whitespace".match(/some_pattern/)
should return nil
but
"nowhitespace".match(/some_pattern/)
should return the MatchData with the entire string. Can anyone suggest a solution for the above?
Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.
A regex to match a string that does not contain only whitespace characters can be written in two ways. The first involves using wildcards (.) and the non-whitespace character set (\S), while the other one involves a positive lookahead to check that the string contains at least one non-whitespace character (\S).
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
Whitespace character: \s. Non-whitespace character: \S.
In Ruby I think it would be
/^\S*$/
This means "start, match any number of non-whitespace characters, end"
You could always search for spaces, an then negate the result:
"str".match(/\s/).nil?
>> "this has whitespace".match(/^\S*$/)
=> nil
>> "nospaces".match(/^\S*$/)
=> #<MatchData "nospaces">
^
= Beginning of string
\S = non-whitespace character, *
= 0 or more
$
= end of string
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