Java Regex - 字母数字,允许前导空格但不允许空白字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17098979/
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
Java Regex - alphanumeric, allowing leading whitespace but not blank string
提问by deanmau5
I've been trying to make a java regex that allows only alphanumeric characters, which can have white spaces, BUT the whole string cannot be blank...
我一直在尝试制作一个只允许字母数字字符的 java 正则表达式,它可以有空格,但整个字符串不能为空...
Few examples..
几个例子..
" hello world123" //fine
"hello123world" //fine
"hello123world " //fine
" " //not allowed
So far I've gotten ^[a-zA-Z0-9][a-zA-Z0-9\s]*$though this does not allow any leading whitespace and so any string with x number leading whitespace is not being matched.
到目前为止,我已经得到 ^[a-zA-Z0-9][a-zA-Z0-9\s]*$虽然这不允许任何前导空格,因此任何带有 x 数字前导空格的字符串都不会匹配.
Any ideas what I could add to the expression to allow leading whitespace?
有什么想法可以添加到表达式中以允许前导空格吗?
回答by David says Reinstate Monica
How about just ^\s*[\da-zA-Z][\da-zA-Z\s]*$
. 0 or more spaces at start, follow by at least 1 digit or letter followed by digits/letters/spaces.
刚刚怎么样^\s*[\da-zA-Z][\da-zA-Z\s]*$
。开头有 0 个或多个空格,后跟至少 1 个数字或字母,后跟数字/字母/空格。
Note: I did not use \w because \w includes "_", which is not alphanumeric.
注意:我没有使用 \w,因为 \w 包括“_”,它不是字母数字。
Edit: Just tested all your cases on regexpal, and all worked as expected. This regex seems like the simplest one.
编辑:刚刚在 regexpal 上测试了所有案例,并且一切都按预期工作。这个正则表达式似乎是最简单的。
回答by Bohemian
Just use a look ahead to assert that there's at least one non-blank:
只需向前看即可断言至少有一个非空白:
(?=.*[^ ])[a-zA-Z0-9 ]+
This may be used as-is with String.matches()
:
这可以按原样使用String.matches()
:
if (input.matches("(?=.*[^ ])[a-zA-Z0-9 ]+")) {
// input is OK
}
回答by Pshemo
You can test it using look-aheadmechanism ^(?=\\s*[a-zA-Z0-9])[a-zA-Z0-9\s]*$
您可以使用前瞻机制对其进行测试^(?=\\s*[a-zA-Z0-9])[a-zA-Z0-9\s]*$
^(?=\\s*[a-zA-Z0-9])
will make regex to check if at start of the string it contains zero of more spaces \\s*
and then character from class [a-zA-Z0-9]
.
^(?=\\s*[a-zA-Z0-9])
将使正则表达式检查在字符串的开头它是否包含零个更多空格\\s*
,然后是 class 中的字符[a-zA-Z0-9]
。
Demo:
演示:
String[] data = {
" hello world123", //fine
"hello123world", //fine
"hello123world ", //fine
" " //not allowed
};
for(String s:data){
System.out.println(s.matches("(?=.*\S)[a-zA-Z0-9\s]*"));
}
output
输出
true
true
true
false