Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: don't match if string contains whitespace

Tags:

regex

ruby

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?

like image 646
Bart Jedrocha Avatar asked Jan 07 '10 04:01

Bart Jedrocha


People also ask

How do I check if a string contains whitespace?

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.

Does not contain whitespace regex?

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).

What is the regex for white space?

\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.

What is a non-whitespace character in regex?

Whitespace character: \s. Non-whitespace character: \S.


3 Answers

In Ruby I think it would be

/^\S*$/

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

like image 199
Danny Roberts Avatar answered Sep 22 '22 23:09

Danny Roberts


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

"str".match(/\s/).nil?
like image 30
Justin Poliey Avatar answered Sep 25 '22 23:09

Justin Poliey


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

^ = Beginning of string

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

$ = end of string

like image 24
Amber Avatar answered Sep 24 '22 23:09

Amber