Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I'm trying to accept a string in a function and check if it's a valid numeric. If it is valid, the function returns True, else False. The valid patterns are:

1) 1234567890.9876543210
2) -1234567890.9876543210
3) -0123456789
4) 9876543210
5) .1234567890
6) 1234567890.25
7) -.1234567890
8) 0

All other patterns should be treated as invalid.

However, if only the negative symbol (-) is supplied, the function still treats it as valid, which goes against my requirement specification. So, how do I ensure that whenever a negative symbol is typed, it must be followed by a digit, or a decimal point followed by a digit? Otherwise, there shouldn't be any negative symbol at all. The user can't supply only the negative symbol. Besides, all the eight patterns listed above should also be counted as valid.

Regards

What I have tried:

private boolean isNumeric(String value) {
    String pattern = "^(-?(\\d+)?(\\.\\d+)?)$";
    return (value != null && !value.equals("") && value.matches(pattern));
}
Posted
Updated 6-Mar-22 21:52pm

1 solution

Try "Breaking it out" and making it simpler with OR:
^-?((\d+)|(\d*\.\d+))$

That allows zero or one "-" followed by a valid number of some form.

If you ar egoign to use Regexes, then get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 
v2
Comments
priyamtheone 11-Mar-22 14:18pm    
Thanks for your help. It's working perfectly. Just one more thing. How do I add a comma as thousand separator to the integer part of the expression? That's the only challenge left now.
OriginalGriff 11-Mar-22 14:19pm    
What have you tried?
priyamtheone 13-Mar-22 11:58am    
This is what I came up with ^[+|-]?(([0-9]\d{0,2}(,?\d{3})*)(\.\d+)?|(\.\d+))$

I think that allows optional thousand separators and also validates the patterns I mentioned in my original post. By far it looks correct to me.
OriginalGriff 13-Mar-22 12:34pm    
Don't "think" ... "test"!

"I think it works" is what my wife says just before she plugs cr@p in and blows every fuse in the house ... :laugh:
priyamtheone 14-Mar-22 15:27pm    
Tested in regex101.com. It validates all the required patterns while dismissing the unrequired ones. Works good in Android Studio too.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900