Hi can some one help me with this I'm trying to use this class java.util.regex.Pattern http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html to make sure that there are no alphabets in a string. before converting it into INT. How can this be done Please help
I'm terrible with Regular Expressions, so I can't help you much. You could do an alternative though -- use another way: public boolean isStringNumeric(str) { try { int num = Integer.parseInt(str); } catch(NumberFormatException e) { return false; } return true; } Code (markup):
You may use the following code snippets to check if the String contains a valid int or not:- ... String intString = "-100"; Pattern p = Pattern.compile( "-?+([0-9]*)" ); /*... '-?+' is to ensure that there is either only one minus sign or not at all. I'm considering here that the positive numbers won't have a preceding plus sign ...*/ Matcher m = p.matcher(intString); m.matches(); /*... it will return true ...*/ ... To enable the RegEx to work well for float also you may like to change this a bit. Find below the code-snippet:- ... String floatString = "-100.05"; Pattern p = Pattern.compile( "-?+([0-9]*)\\.([0-9]*)" ); /*... '\\.' is to accept the decimal point ...*/ Matcher m = p.matcher(floatString); m.matches(); /*... it will return true ...*/ ... Note: in both the cases I've assumed that the String doesn't contain any whitespace characters otherwise you will need to use [ \t\n\x0B\f\r] to test them as well. I hope this helps you writing the actual code suitable as per your actual requirements. Please let me know in case you needed to do something else to implement your requirements. Thanks, Geek http://geekexplains.blogspot.com
Good that you were able to solve it. Today I wrote a complete Java program using Regular Expressions which identifies Strings representing Numbers (int/float). The Strings can have leading, trailing, and/or embedded spaces. I've posted it to my blog with complete explanation. You may like to have a look at it. The URL of the post is: http://geekexplains.blogspot.com/2008/08/using-reg-ex-to-identify-strings.html Thanks, Geek