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?
Asked
Active
Viewed 49 times
1 Answers
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+)?$
CyberStems
- 293
- 1
- 14
-
1Thank you, this is probably the best approach, I appreciate your answer. – SpaceSpaghetti Dec 02 '19 at 23:38