How to split a string into integer positive and negative numbers?

I am writing a program to perform various calculations using vector functions, but the program that I currently limit to negative numbers. I tried using different delimiters, but I can not find the correct option.

Does anyone know how to keep positive and negative digits when splitting a string? Also, is there a way to store decimal values? .45 will return 45 and .29 will return 29

This is the code:

ArrayList<Integer> list = new ArrayList<Integer>();

String twoVectors = "a=<-1,2,-3> b=<4,-5,6>"; // vector and a and b

String[] tokens = twoVectors.split("\\D");

for (String s : tokens)
    if (!s.equals(""))
        list.add(Integer.parseInt(s));

System.out.println(Arrays.toString(list.toArray()));

When I run the program, I get [1, 2, 3, 4, 5, 6] instead of [-1, 2, -3, 4, -5, 6]. All the functions that I worked fine, but do not work when using negative values.

Any help would be appreciated.

+4
4

    String[] tokens = twoVectors.split("[^\\d-]+");

[^\\d-]+: , , -

[]: , []

^: (\\d-)

\\d-: 0-9 -

- Regex


    String twoVectors = "a=<-1,2,-3> b=<4,-5,6>";

    ArrayList<Integer> list = new ArrayList<Integer>();

    String[] tokens = twoVectors.split("[^\\d-]");

    for (String s : tokens)
        if (!s.equals(""))
            list.add(Integer.parseInt(s));

    System.out.println(Arrays.toString(list.toArray()));

:

[-1, 2, -3, 4, -5, 6]

Pattern matcher, , , -?\\d+ regex

Regex Demo -?\d+


: Double [^\\d-.]+ Double Integer Double.parseDouble

Pattern matcher -?\\d*\\.?\\d+

+3

, , . , , . - , , -, . , , - . .

, (, -?\d*.?\d+), . Double, .

String twoVectors = "a=<-1,.2,-3> b=<4,-5,6>";

ArrayList<Double> numbers = new ArrayList<Double>();

Matcher matcher = Pattern.compile("-?\\d*\\.?\\d+").matcher(twoVectors);    
while (matcher.find()) {
   numbers.add(Double.parseDouble(matcher.group()));
}
System.out.println(Arrays.toString(numbers.toArray()));

[-1.0, 0.2, -3.0, 4.0, -5.0, 6.0]

+1

[^\\d-] split, .. twoVectors.split("[^\\d-]")

[^\\d-]:

^: , .

\d: [0-9]

-: '-',

0

:

List<Integer> numbers = Arrays
  .stream(twoVectors.replaceAll("^[^\\d-]+", "").split("[^\\d-]+"))
  .map(Integer::new)
  .collect(Collectors.toList());

The initial replacement is to remove the leading non-target characters (otherwise a split will return empty in the first element).

0
source

Source: https://habr.com/ru/post/1670147/


All Articles