0

I was wondering if you could check the elements in an array of strings, to see if they could be parsed into an int or double? I know you could try to parse the element and handle the exception thrown but is there another way?

  • Does this answer your question? [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – SDJ Dec 02 '19 at 18:33

1 Answers1

1

use a regex like this -?\d+(.\d+)?

-?     --> optional negative symbol
\d+    --> indicates a sequence of one or more numbers
.?     --> optional decimal (for floats)
(\d+)? --> optional digits following the decimal

the command to match would be like str.matches("-?\\d+(.\\d+)?"); and I'd just iterate through it with an enhanced for loop. String.matches() is a built in boolean function so if the string can't be converted to a float or int then it'll return false.

the double \\ is just to escape a literal \ character.

If you don't want the pattern to match something like a portion of fewkjnf12.345r52v then simply just add a carat to indicate that the beginning of the float/int should have no strings, and a dollar sign to the end of the string to ensure nothing comes after it

i.e ^-?\d+(.\d+)?$

please visit this site to see the regex in action

CyberStems
  • 293
  • 1
  • 14