如何检查此字符串匹配哪种模式?

问题描述 投票:1回答:1
String numFormatPattern1 = "-$###,###.00";
String numFormatPattern2 = "-$###,###.00";
String numFormatPattern3 = "€###.###,00-";
... 
String value = "-$999,222,333.33";

该值可能类似于98.99,-$ 89,898,989.99,$ 89,898,989.99-,€43.43etc任何有或没有货币符号的货币,负号可以在结尾或开头,任何长度我有一个用于金额的字符串,我需要检查此字符串是否与模式匹配,有人知道吗?

java string currency
1个回答
0
投票

我将使用给定的格式解析字符串,然后使用相同的格式将其格式化回字符串。

public static void main(String[] args) {
    String pattern = "-$###,###.00";
    String s = "-$999,222,333.33";

    DecimalFormat format = new DecimalFormat(pattern);

    boolean matches = false;

    try {
        if (format.format(format.parse(s)).equals(s)) {
            matches = true;
        }
    } catch (ParseException ignored) {}

    System.out.println("Matches: " + matches);
}

请记住,在解析和格式化时使用的数字分隔符对语言环境敏感。

© www.soinside.com 2019 - 2024. All rights reserved.