正则表达式为非空
我需要一个Java正则表达式,它检查给定的String不是Empty。 但是,如果用户在输入的开头意外地给出了空格,那么表达式应该是无意义的,但稍后允许空格。 表达式应该允许斯堪的纳维亚字母,Ä,Ö等,包括小写和大写。
我用谷歌搜索了,但似乎没有什么能满足我的需求。 请帮忙。
您还可以使用正向前瞻断言断言该字符串至少包含一个非空白字符:
^(?=\s*\S).*$
在Java中你需要
"^(?=\\s*\\S).*$"
对于非空字符串,请使用.+
。
这应该工作:
/^\s*\S.*$/
但正则表达式可能不是最佳解决方案,具体取决于您的其他想法。
^\s*\S
(在开头跳过任何空格,然后匹配不是空白的东西)
为了测试非空输入,我使用:
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
你不需要正则表达式。 这工作,更清晰,更快:
if(myString.trim().length() > 0)
为此创建方法比使用正则表达式更快
/** * 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()); }