[英]How do I write a regex in java which allow only numbers 0-9 and #
I want the user to input only numbers 0-9 and '#' No spaces, no alphabets and no other special characters. 我希望用户仅输入数字0-9和'#',不能输入空格,字母和其他特殊字符。
For ex: 例如:
12736#44426 :true
263 35# :false
2376shdbj# :false
3623t27# :false
#? :false
Here's my code: 这是我的代码:
boolean valid(String str)
{
if(str.matches("[0-9]+|(\\#)"))
return true;
else
return false;
}
But it returns false for 3256#
但是它为
3256#
返回false
I also tried [0-9]+|(#)
我也试过
[0-9]+|(#)
I am very noob at regular expressions. 我对正则表达式非常陌生。
Any help would be appreciated. 任何帮助,将不胜感激。
Tell me if i am not clear. 告诉我是否不清楚。
将#
字符添加到您的字符类中,而不使用替代运算符。
[0-9#]+
You can use a regex like this: 您可以使用以下正则表达式:
^[\d#]+$
The idea is to match digits and symbol # by using using the pattern [\\d#]
and can be many 1 or many times (using +
). 这个想法是通过使用模式
[\\d#]
来匹配数字和符号#,并且可以是1或很多次(使用+
)。 And to ensure that the line starts and ends with those characters I use anchors ^
(start of the line) and $
(end of line). 为了确保行以这些字符开头和结尾,我使用了锚点
^
(行的开头)和$
(行的结尾)。
For java remember to escape backslahes as: 对于Java,请记住将后缀转义为:
^[\\d#]+$
The java code you can use can be: 您可以使用的Java代码可以是:
Pattern pattern = Pattern.compile("^[\\d#]+$");
Matcher matcher = pattern.matcher(YOUR TEXT HERE);
if (matcher.find()) {
System.out.println("matches!");
}
Or also: 或者:
if ("YOUR STRING HERE".matches("^[\\d#]+$")) {
System.out.println("matches!");
}
If you want to know more about the usage you can check this link: 如果您想进一步了解用法,可以查看以下链接:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#regexjava http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#regexjava
^[0-9#]+$
尝试一下。这将为您提供结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.