Reputation: 71
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?
Upvotes: 0
Views: 76
Reputation: 358
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
Upvotes: 1