簡體   English   中英

Java中的正則表達式用於解析錢

[英]Regular expression in Java for parsing money

我正在尋找用於解析金額的正則表達式。 字符串s10不應匹配。 有人可以幫忙嗎,或者有人可以簡化正則表達式嗎? 這是我的嘗試:

    public static String[] getMoney(String s) {
        List<String> ret = new ArrayList<String>();
        String regex = "((\\d{1,3}[.,]?)(\\d{3}[.,]?)*[.,]\\d{1,2})(\\D|$)";
        Pattern pat = Pattern.compile(regex);
        Matcher mat = pat.matcher(s);
        while (mat.find()) {
            ret.add(mat.group(1));
        }
        return ret.toArray(new String[0]);
    }

    public static void main(String[] args) {
        String s1 = "0,1"; // should match
        String s2 = ",1"; // should not match
        String s3 = "1,"; // should not match
        String s4 = "1.234,01"; // should match
        String s5 = "1234,10"; // should match
        String s6 = "1234,100"; // should not match
        String s7 = "1234,10a"; // should match
        String s8 = "123,456,789.10"; // should match
        String s9 = "123.456.789,10"; // should match
        String s10 = "123,456.789,10"; // should not match (!)

        System.out.println(Arrays.toString(getMoney(s1)));
        System.out.println(Arrays.toString(getMoney(s2)));
        System.out.println(Arrays.toString(getMoney(s3)));
        System.out.println(Arrays.toString(getMoney(s4)));
        System.out.println(Arrays.toString(getMoney(s5)));
        System.out.println(Arrays.toString(getMoney(s6)));
        System.out.println(Arrays.toString(getMoney(s7)));
        System.out.println(Arrays.toString(getMoney(s8)));
        System.out.println(Arrays.toString(getMoney(s9)));
        System.out.println(Arrays.toString(getMoney(s10)));
    }

我想你可以使用

(?<![\d,.])(?:\d{1,3}(?:(?=([.,]))(?:\1\d{3})*)?|\d+)(?:(?!\1)[.,]\d{1,2})?(?![,.\d])

查看正則表達式演示

細節

  • (?<,[\d..]) - 沒有數字, . ,允許立即在左側
  • (?:\d{1,3}(?:(?=([.,]))(?:\1\d{3})*)?|\d+) -
    • \d{1,3}(?:(?=([.,]))(?:\1\d{3})*)? - 一位、兩位或三位數字,后跟可選的 position 后跟逗號或點,后跟 0 次或多次捕獲的值,然后是任意三位
    • |\d+ - 或 1 位或多位數字
  • (?:(?.\1)[,,]\d{1?2})? - 逗號或點的可選序列,但與第 1 組中的字符不同,然后是 1 或 2 位數字
  • (?,[..\d]) - 沒有數字, . ,立即允許在右側

在 Java 中,不要忘記將反斜杠加倍:

String regex = "(?<![\\d,.])(?:\\d{1,3}(?:(?=([.,]))(?:\\1\\d{3})*)?|\\d+)(?:(?!\\1)[.,]\\d{1,2})?(?![,.\\d])";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM