Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for not empty and not whitespace

I am trying to create a regex that will return false if the String pattern contains whitespace or is empty. So far I have this

[^\s]  

I think that will make sure the string does not contain whitespace but I am unsure of how to also check to make sure it is not empty. Any help would be appreciated.

like image 311
medium Avatar asked Nov 01 '11 13:11

medium


People also ask

What is a non-whitespace character in regex?

Non-whitespace character: \S.

What does \d mean in regex?

In regex, the uppercase metacharacter is always the inverse of the lowercase counterpart. \d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.

Does whitespace matter in regex?

Match Whitespace Characters in Python? Yes, the dot regex matches whitespace characters when using Python's re module.


2 Answers

/^$|\s+/ if this matched, there's whitespace or its empty.

like image 187
Jan. Avatar answered Sep 21 '22 09:09

Jan.


In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:

(.|\s)*\S(.|\s)* 

This matches any string containing at least one non-whitespace character (the \S in the middle). It can be preceded and followed by anything, any character or whitespace sequence (including new lines): (.|\s)*.

You can try it with explanation on regex101.

like image 26
Tony Avatar answered Sep 20 '22 09:09

Tony