0

Here is my program and it's work if my input is somthing like that: asd12jjh-23lm100k but if I have two negative numbers one after one asd123kk-23-51llk the regex expression do not work. So I need help how to change my expression to get all numbers from string with - sign and then print them and calculate the sum of all elements.

import java.util.Scanner;
public class Task9 {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string with digits,characters and sign");
    String sentecen = sc.nextLine();
    int sum = 0;
    String []splitedNumbers = sentecen.split("[^0-9-]+");
    for (int i = 1; i < splitedNumbers.length; i++) {
    sum+=Integer.parseInt(splitedNumbers[i]);   
    }
    for(String check:splitedNumbers){
        System.out.println(check);
    }
    System.out.println(sum);
}

}
Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

4
[^0-9-]+

is a character class that captures all contiguous (next-to-each-other) digit or dash characters. That's why -123-124 is being seen as a single unit, which you don't want.

A positive number in this context, means

A digit that is either the first character in the string, or the first to immediately-follow a non-digit/non-dash character.

This regex will extract all positive numbers:

(?:^|(?<![-0-9]))([0-9]+)

Regular expression visualization

Debuggex Demo

It says that the position before the digit must be either the beginning of the string (^) ... or (|) contain any character other than a dash or digit ((?<![-0-9])). The latter is a negative look-behind.

A negative number in this context means

A digit that does have a dash before it, and is therefore not the first character in the string.

This regex will extract all negative numbers:

(-[0-9]+)

Regular expression visualization

Debuggex Demo

It says "find a dash, followed immediately by one or more digits".


If you don't have to do this parsing in a single regex, don't. Why make it more complicated than it needs to be? Analyze the string in two passes. First to extract the positive numbers, second for the negative, then do as you will.


Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference.

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • @RumenGergushki: If this answer helped you, please consider upvoting and accepting it, by clicking on the big green checkmark. Best of luck, and welcome to Stack Overflow! – aliteralmind Mar 25 '15 at 18:02
1

You can test your regex at this site;

You can use the regex "[0-9]+|[-][0-9]+" to retrieve all the numbers and then make the sum.

You can find the Regular expression pattern here