Bart Jedrocha
Bart Jedrocha

Reputation: 11570

Regex: don't match if string contains whitespace

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

Answers (7)

Justin Poliey
Justin Poliey

Reputation: 16341

You could always search for spaces, an then negate the result:

"str".match(/\s/).nil?

Upvotes: 4

kejadlen
kejadlen

Reputation: 1599

str.match(/^\S*some_pattern\S*$/)

Upvotes: 0

mletterle
mletterle

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

Amber
Amber

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

Brian Campbell
Brian Campbell

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

John Weldon
John Weldon

Reputation: 40749

   "nowhitespace".match(/^[^\s]*$/)

Upvotes: 1

Danny Roberts
Danny Roberts

Reputation: 3572

In Ruby I think it would be

/^\S*$/

This means "start, match any number of non-whitespace characters, end"

Upvotes: 24

Related Questions