Extracting number in java string
I have a pretty simple question: I have line 0-1000 let's say str = "0-1000"
I am successfully fetching 0 and 1000 with str.split("-")
I am now tasked with checking the number because I noticed that these two numbers can be negative.
If I continue str.split("-")
, I will also miss the negative sign.
Can anyone suggest me methods?
source to share
Since it String.split()
uses regular expressions for separation, you can do something like this:
String[] nos = "-1000--1".split("(?<=\\d)-";
This means that you are separating the minus characters that follow the digit, i.e. must be the operator.
Note that you need to use a positive look-behind (?<=\d)
as you only want to match the minus character. String.split()
removes all matching delimiters and thus something like \d-
removes digits as well.
To parse the numbers you then iterate over the elements of the array and call Integer.valueOf(element)
or Integer.parseInt(element)
.
Note that this assumes the input string is valid. Depending on what you want to achieve, you first need to check the input to match, eg. using -?\d--?\d
to check if a string is in a format x-y
where x
and y
can be positive or negative integers.
source to share