11

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?

2
  • are you trying to determine if a string contains whitespace, or if a string contains a certain pattern but ONLY if there no whitespace? Commented Jan 7, 2010 at 4:22
  • Basically I want match to return nil if the string contains whitespace . Commented Jan 7, 2010 at 4:57

7 Answers 7

24

In Ruby I think it would be

/^\S*$/

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

Sign up to request clarification or add additional context in comments.

6 Comments

Ahh! I was missing the end of line anchor at the end. Cheers!
@Bart, note that \n and \r are also considered white space characters.
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"
I won't have to worry about multi-line strings in my application but that's an excellent point - thanks.
What about /^\S*$/m, where m turns on a multiline mode? :)
|
4

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

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

Comments

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

^ = Beginning of string

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

$ = end of string

Comments

3

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

"string".match(/pattern/) unless "string".match(/\s/)

1 Comment

+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...
1
   "nowhitespace".match(/^[^\s]*$/)

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.