3

I have a quite simple question here is that i have a string 0-1000 say str = "0-1000"

I successfully extract 0 and 1000 by using str.split("-")

Now, I am assigned to check the number because i am noticed that those two numbers can be a negative.

If I continue str.split("-"), then I will skip the negative sign as well.

Could anyone suggest methods for me?

3
  • please post an example of string containing negative number Commented Apr 28, 2015 at 10:27
  • 1
    Coudl you give an example of how a String containing negative numbers would look? Would this be 0--1000? Commented Apr 28, 2015 at 10:27
  • @JohannisK I have edited with an example Commented Apr 28, 2015 at 10:29

2 Answers 2

4

Since String.split() uses regular expressions to split, you could do something like this:

String[] nos = "-1000--1".split("(?<=\\d)-";

This means you split at minus characters that follow a digit, i.e. must be an operator.

Note that the positive look-behind (?<=\d) needs to be used since you only want to match the minus character. String.split() removes all matching separators and thus something like \d- would remove digits as well.

To parse the numbers you'd then iterate over the array elements and call Integer.valueOf(element) or Integer.parseInt(element).

Note that this assumes the input string to be valid. Depending on what you want to achieve, you might first have to check the input for a match, e.g. by using -?\d--?\d to check whether the string is in format x-y where x and y can be positive or negative integers.

Sign up to request clarification or add additional context in comments.

5 Comments

oh thanks but the one -1000 in your example is still a string.
does it know 1000 is a digit
@rickyma924 - to parse it into a Integer use Integer.parseInt()
@rickyma924 1000 is not a digit but a string of 4 digit characters. As TheLostMind already commented you need to parse the numbers to integers in any case.
I know the part of parseInt
4

You can use regex like this :Works for all cases

public static void main(String[] args) {
    String s = "-500--578";
    String[] arr = s.split("(?<=\\d)-"); // split on "-" only if it is preceeded by a digit
    for (String str : arr)
        System.out.println(str);
}

O/P:

-500
-578

6 Comments

@JordiCastilla - You love it like you hate it? :P
is it \\d\\- enough to do what i want?
@rickyma924 no, since you don't want the digit to be part of the separator. Hence you need to use a zero-width positive look-behind, i.e. (?<=\d)
@TheLostMind yes... I love them because are super powerfull... but I hate them because I'm so bad with them... XD
Actually I still don't understand "(?<=\\d)\\-"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.