Java 非空的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4448829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:39:15  来源:igfitidea点击:

Regular expression for not empty

javaregex

提问by jaana

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 beginning of the input, but allow whitespaces later on. Also the expression should allow scandinavian letters, ?,? and so on, both lower and uppercase.

我需要一个 Java 正则表达式,它检查给定的字符串是否为空。然而,如果用户在输入的开头不小心给出了空格,则表达式应该忽略,但稍后允许空格。此外,表达式应该允许斯堪的纳维亚字母,?,? 等等,小写和大写。

I have googled, but nothing seems ro quite fit on my needs. Please help.

我用谷歌搜索过,但似乎没有什么能满足我的需求。请帮忙。

回答by The Archetypal Paul

^\s*\S

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

(在开始时跳过任何空格,然后匹配不是空格的东西)

回答by sjngm

This should work:

这应该有效:

/^\s*\S.*$/

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

但正则表达式可能不是最佳解决方案,这取决于您还有什么想法。

回答by Michael Borgwardt

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

您不需要为此使用正则表达式。这有效,更清晰,更快:

if(myString.trim().length() > 0)

回答by Shervin Asgari

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());
}

回答by codaddict

You can also use positive lookahead assertionto assert that the string has atleast one non-whitespace character:

您还可以使用正向先行断言来断言该字符串至少有一个非空白字符:

^(?=\s*\S).*$

In Java you need

在 Java 中你需要

"^(?=\s*\S).*$"

回答by Rob Krabbendam

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 

回答by Lavish

For a non empty String use .+.

对于非空字符串,请使用.+.