Regular expression to extract all possible sums

I am looking for a regular expression that will extract all possible sums from a string, assuming that the sums always contain 2 decimal places and accept either ., or ,as delimiters. For example, for the next line, I would like to find the following amounts:

1.234,567.89

1.23
1.234,56
  234,56
   34,56
    4,56
1.234,567.89
  234,567.89
   34,567.89
    4,567.89
      567.89
       67.89
        7.89

Is this achievable with regex?

My current regex ?\\d{1,3}([\\.,]\\d{3})*([\\.,]\\d{2}), but that obviously doesn't work, because it returns only 1 match.

+4
source share
1 answer

So, initially I thought it was impossible to do with regex. I was wrong about this, but this is only possible by removing duplicates and empty strings / zeros.

Regex

See regex expression here

(?=(\d+[.,]\d{2}))(?=((?:\d+[.,]){2,}?\d{2})?)(?=((?:\d+[.,])+\d{2}))

3 . :

  • (?=(\d+[.,]\d{2}))
    • (\d+[.,]\d{2}) 1. , 1.23.
      • \d+
      • [.,] . ,
      • \d{2} 2
  • (?=((?:\d+[.,]){2,}?\d{2})?)
    • ((?:\d+[.,]){2,}?\d{2})? 2. , 1.234,56, (1.23 1.234,567.89 ). , , , {2,} {3,}, {4,} .. while. , , ( ).
      • (?:\d+[.,]){2,}? 2 , .
        • \d+
        • [.,] . ,
      • \d{2}
  • (?=((?:\d+[.,])+\d{2}))
    • ((?:\d+[.,])+\d{2}) 3. , 1.234,567.89.
      • (?:\d+[.,])+
        • \d+
        • [.,] . ,
      • \d{2} 2

, List. null , . Set ( ) .

,

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main{
    public static void main(String[] args) {
        String s = "1.234,567.89";
        Pattern p = Pattern.compile("(?=(\\d+[.,]\\d{2}))(?=((?:\\d+[.,]){2,}?\\d{2})?)(?=((?:\\d+[.,])+\\d{2}))");
        Matcher m = p.matcher(s);

        List<String> al = new ArrayList<>();
        Set<String> hs = new HashSet<>();

        while(m.find()) {
            al.add(m.group(1));
            al.add(m.group(2));
            al.add(m.group(3));
        }

        al.removeAll(Collections.singleton(null));
        hs.addAll(al);
        al.clear();
        al.addAll(hs);

        System.out.println(al);
    }
}

OP ( , , ).

[34,567.89, 4,56, 7.89, 234,56, 4,567.89, 1.234,56, 1.23, 1.234,567.89, 34,56, 567.89, 67.89, 234,567.89]
+5

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


All Articles