Please tell me which pattern I need to use if field must not contain only spaces.
            Asked
            
        
        
            Active
            
        
            Viewed 1.9k times
        
    5 Answers
15
            Why need to use regex?
str.trim().isEmpty()
        xdazz
        
- 158,678
 - 38
 - 247
 - 274
 
- 
                    this generates a copy of a string object, not sure it outperforms regex – Jean-François Fabre Dec 29 '22 at 16:30
 
15
            
            
        You must use this pattern.
.*[^ ].*
It can be anything but not only spaces.
        Caner Korkmaz
        
- 407
 - 4
 - 11
 
- 
                    
 - 
                    you may need to add a `/ /g` flag, but this is the simplest answer – Beerswiller Nov 25 '22 at 02:56
 
2
            
            
        assuming you mean any whitespace, not just spaces, \S will work.
Cfr every dev's must-have friend, The regex cheat sheet
        Joeri Hendrickx
        
- 16,947
 - 4
 - 41
 - 53
 
- 
                    field could be "Hi i am" but could not be " ". It can contain spaces but not only spaces – Sep 24 '12 at 15:48
 - 
                    @KirillBazarov: If your string matches \S it means that it has at least one character that is not a whitespace. It still can contain whitespaces. – Daniel Hilgarth Sep 24 '12 at 15:50
 - 
                    
 
2
            
            
        I've got one, it seems heavy, but it's not that hard to implement.
Pattern with no blank:
^[pattern]\*[pattern without space][pattern]*$
Example:
-pattern: a-zA-ZÀ-ÿ '\-
(note that it allows spaces)
[a-zA-ZÀ-ÿ '\-]
With no blank =
^[a-zA-ZÀ-ÿ '\-]\*[a-zA-ZÀ-ÿ'\-][a-zA-ZÀ-ÿ '\-]*
Of course, if you don't allow spaces at all, you don't need to do that.
You can test yours on https://regexr.com/.
0
            
            
        This is much simple .If you are using java just code this. As example:-
classVariable.getname().trim().equal("")
by this you can check whether that variable contains only spaces.
        Susampath
        
- 706
 - 10
 - 13