Regex for not empty and not whitespace

2020-02-09 00:08发布

问题:

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.

回答1:

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



回答2:

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 char or whitespace sequence (including new lines) - (.|\s)*.

You can try it with explanation on https://regex101.com/.



回答3:

Most regular expression engines support "counter part" escape sequences. That is, for \s (white-space) there's its counter part \S (non-white-space).

Using this, you can check, if there is at least one non-white-space character with ^\S+$.

PCRE for PHP has several of these escape sequences.



回答4:

I ended up using something similar to the accepted answer, with minor modifications

(^$)|(\s+$)

Explanation by the Expresso

Select from 2 alternatives (^$)
    [1] A numbered captured group ^$
        Beginning of line ^
        End of line $
    [2] A numbered captured group (\s+$)
        Whitespace, one or more repetitions \s+
        End of line $


回答5:

A little late, but here's a regex I found that returns 0 matches for empty or white spaces:

/^(?!\s*$).+/

You can test this out at regex101



回答6:

/^$|\s+/ This matches when empty or white spaces

/(?!^$)([^\s])/ This matches when its not empty or white spaces



回答7:

/^[\s]*$/ matches empty strings and strings containing whitespaces only