tags:

views:

299

answers:

7

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?

+3  A: 
>> "this has whitespace".match(/^\S*$/)
=> nil
>> "nospaces".match(/^\S*$/)
=> #<MatchData "nospaces">

^ = Beginning of string

\S = non-whitespace character, * = 0 or more

$ = end of string

Amber
+8  A: 

In Ruby I think it would be

/^\S*$/

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

Danny Roberts
Ahh! I was missing the end of line anchor at the end. Cheers!
Bart Jedrocha
@Bart, note that `\n` and `\r` are also considered white space characters.
Bart Kiers
You might want `/\A\S*\Z/` instead, as this will match the start and end of the string rather than the start and end of lines. `"lineone\nlinetwo"` matched with `/^\S*$/` will return `"lineone"`
Ben Marini
I won't have to worry about multi-line strings in my application but that's an excellent point - thanks.
Bart Jedrocha
A: 
   "nowhitespace".match(/^[^\s]*$/)
John Weldon
+1  A: 

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.

Brian Campbell
+2  A: 

Not sure you can do it in one pattern, but you can do something like:

"string".match(/pattern/) unless "string".match(/\s/)
mletterle
+1 for thinking about the question differently... the question could be interpreted as match a string containing pattern 'x' as long as the string does not include whitespace...
John Weldon
A: 

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

kejadlen
+2  A: 

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

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