How do I write a regex in java which allow only numbers 0-9 and # -
i want user input numbers 0-9 , '#' no spaces, no alphabets , no other special characters.
for ex:
12736#44426 :true 263 35# :false 2376shdbj# :false 3623t27# :false #? :false here's code:
boolean valid(string str) { if(str.matches("[0-9]+|(\\#)")) return true; else return false; } but returns false 3256#
i tried [0-9]+|(#)
i noob @ regular expressions.
any appreciated.
tell me if not clear.
you can use regex this:
^[\d#]+$ 
the idea match digits , symbol # using using pattern [\d#] , can many 1 or many times (using +). , ensure line starts , ends characters use anchors ^ (start of line) , $ (end of line).
for java remember escape backslahes as:
^[\\d#]+$ the java code can use can be:
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 want know more usage can check link:
http://www.vogella.com/tutorials/javaregularexpressions/article.html#regexjava
Comments
Post a Comment