Reputation: 11570
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?
Upvotes: 11
Views: 27127
Reputation: 16341
You could always search for spaces, an then negate the result:
"str".match(/\s/).nil?
Upvotes: 4
Reputation: 3968
Not sure you can do it in one pattern, but you can do something like:
"string".match(/pattern/) unless "string".match(/\s/)
Upvotes: 3
Reputation: 526573
>> "this has whitespace".match(/^\S*$/)
=> nil
>> "nospaces".match(/^\S*$/)
=> #<MatchData "nospaces">
^
= Beginning of string
\S = non-whitespace character, *
= 0 or more
$
= end of string
Upvotes: 3
Reputation: 332776
You want:
/^\S*$/
That says "match the beginning of the string, then zero or more non-whitespace characters, then the end of the string." The convention for pre-defined character classes is that a lowercase letter refers to a class, while an uppercase letter refers to its negation. Thus, \s
refers to whitespace characters, while \S
refers to non-whitespace.
Upvotes: 1
Reputation: 3572
In Ruby I think it would be
/^\S*$/
This means "start, match any number of non-whitespace characters, end"
Upvotes: 24