Regular expression for not empty

后端 未结 7 1239
执笔经年
执笔经年 2020-12-28 18:31

I need a Java regular expression, which checks that the given String is not Empty. However the expression should ingnore if the user has accidentally given whitespace in the

相关标签:
7条回答
  • 2020-12-28 18:54

    It's faster to create a method for this rather than using regular expression

    /**
     * This method takes String as parameter
     * and checks if it is null or empty.
     * 
     * @param value - The value that will get checked. 
     * Returns the value of "".equals(value). 
     * This is also trimmed, so that "     " returns true
     * @return - true if object is null or empty
     */
    public static boolean empty(String value) {
        if(value == null)
            return true;
    
        return "".equals(value.trim());
    }
    
    0 讨论(0)
  • 2020-12-28 19:01

    This should work:

    /^\s*\S.*$/
    

    but a regular expression might not be the best solution depending on what else you have in mind.

    0 讨论(0)
  • 2020-12-28 19:02
    ^\s*\S
    

    (skip any whitespace at the start, then match something that's not whitespace)

    0 讨论(0)
  • 2020-12-28 19:09

    For a non empty String use .+.

    0 讨论(0)
  • 2020-12-28 19:11

    For testing on non-empty input I use:

    private static final String REGEX_NON_EMPTY = ".*\\S.*"; 
    // any number of whatever character followed by 1 or more non-whitespace chars, followed by any number of whatever character 
    
    0 讨论(0)
  • 2020-12-28 19:14

    You don't need a regexp for this. This works, is clearer and faster:

    if(myString.trim().length() > 0)
    
    0 讨论(0)
提交回复
热议问题