Java validating strings for digits

You can do a lot studying each digit or matching expressions but it's a lot of effort to accept every valid int and reject every invalid one, and even more work for floating types.You can make a short method like this: Ok, I agree that the try/catch method would be the easiest and it is funny that someone mentioned that accounting for floats would add to the hassle.String a = "12.0"; //Valid String b = "12.5"; //Invalid Pattern p = Pattern.compile( "([0-9]*)\.[0]" ); Matcher m = p.matcher(a); m.matches(); //TRUE Matcher m = p.matcher(b); m.matches(); //FALSE I think this will be me over the hump unless anyone can predict some scenarios where I may miss some data. Regular expressions also use escape characters because some characters like '.' have special meaning.So if you want a literal '.', you have to escape it as "\.".Turns out, all the valid integers I need are actually being stored as floats which invalidates everything. When I grab the data from a column where I expect the data to be a cell type of numeric, I actually get a float represenation of the value (e.g. When I test that value using the regex API pattern [0-9]* it fails because the value is a float.But floats should fail because 12.5 would be an invalid value.Of course, you already know this since you seem to have written the regex to take this into account.This becomes a problem because Java sees the regex as a String before it passes it on to the regex library.

Just looking for a thums-up/thumbs-down or a possible alternative. OR: You could iterate along the string and try At(i)Digit(); Anybody suggest a better way with a regular expression?

This is because "\" stands for a literal backslash to the regex library.

But to get two backslashes in a Java String, you need to escape both of them, as in "\\".

Regular expressions are a powerful and robust way of matching text against a pattern.

A typical Regular expression is composed of a combination of symbols, metacharacters and quantifiers appearing in a certain order to form a pattern.

Leave a Reply