Java validating strings for digits

Posted by / 27-Oct-2017 07:21

Java validating strings for digits

I'm new to Java and don't know what the fastest, efficient methods are however.

I was able to solve this by using this following code provided by a comment on this question. What I used that worked came from the first comment. \d*$" will compare the whole string and only match if it is a valid number (negatives and decimals included).

Is it really worth adding a whole library for this feature though?

Obviously if it's used with other stuff that's great, but it's probably overkill considering people have solved this in one line of code.

I tried with below examples, but both of them returned me false as result.

Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

Although all the example codes provided seems to be valid as well! For example, it will match 1, 10, 1.0, -1, -1.0, etc.

It'll also match on "1." but that can often be parsed anyway. If you don't mind the (extremely) minor performance hit--which is probably no worse than doing a regex match--use Integer.parse Int() or Double.parse Double().

It is a good idea to start studying reg(ular) ex(presions) because they are useful in string formatting (Imagine that you have to test if the input is a valid email...).

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case: String regex = "\d "; // positive test cases, should all be "true" println("1".matches(regex)); println("12345".matches(regex)); println("123456789".matches(regex)); // negative test cases, should all be "false" println("".matches(regex)); println("foo".matches(regex)); println("aa123bb".matches(regex)); (even though it is also correct). Please note that if you use an online "regex checker" then this may behave differently.

To match fragments of a string in Java, you can use the Pattern pattern = Pattern.compile(regex); println(pattern.matcher("1").matches()); println(pattern.matcher("12345").matches()); println(pattern.matcher("123456789").matches()); and catch exception, it handles minus sign. (i am not arguing with your point, but I think my answer can still be useful in some cases).

Convert it to a char array, "a1"Char Array() Compare char[0] to your fields 'a'....'h' you can use == now that its a primitive, as in chars[0] == 'a'. If you do this, you'll have to compare to the character values. Looks like you should make two lists, loop through them (nested), then test if the concatenated list values are ==.

Like ((my List(index Outer) my2nd List(index Inner)) == "the List Holding Your Strings(string Index)).

java validating strings for digits-38java validating strings for digits-7java validating strings for digits-31

name.matches("[a-z A-Z_] ")) String number; println("Enter number:"); number = Line(); if (!