带货币符号数字的自动识别、提取及多货币Locale匹配方案咨询
识别并提取带货币符号的金额(支持多货币)
Java原生方案
Java原生的NumberFormat结合Currency和Locale可实现基础多货币识别与解析,核心思路是遍历可用Locale,尝试用对应区域的货币格式解析文本:
import java.text.NumberFormat; import java.util.Currency; import java.util.Locale; public class CurrencyExtractor { public static void extractCurrencyAmount(String text) { for (Locale locale : NumberFormat.getAvailableLocales()) { try { NumberFormat nf = NumberFormat.getCurrencyInstance(locale); nf.setParseIntegerOnly(false); Number number = nf.parse(text); Currency currency = nf.getCurrency(); System.out.printf("识别到货币:%s,金额:%f,Locale:%s%n", currency.getSymbol(locale), number.doubleValue(), locale); break; // 找到匹配后终止遍历 } catch (Exception e) { // 当前Locale不匹配,继续尝试下一个 continue; } } } public static void main(String[] args) { String textWithCurrency = "د.ع. 40,986.63"; extractCurrencyAmount(textWithCurrency); } }
原生方案的局限性在于对部分小众或非拉丁系货币的识别支持有限,遍历Locale的效率也一般,适合需求不极端的场景。
第三方库方案(ICU4J)
如果需要支持近180种货币,尤其是阿拉伯这类复杂符号的货币,ICU4J是更优选择——它对全球货币和Locale的支持远超Java原生,识别准确率和解析效率更高。
依赖引入(Maven)
<dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>74.1</version> <!-- 使用最新稳定版本 --> </dependency>
示例代码
import com.ibm.icu.text.NumberFormat; import com.ibm.icu.util.Currency; import com.ibm.icu.util.ULocale; public class ICUCurrencyExtractor { public static void extractCurrencyAmount(String text) { // 已知目标货币对应的Locale时可直接指定 try { NumberFormat nf = NumberFormat.getCurrencyInstance(new ULocale("ar_DZ")); Number number = nf.parse(text); Currency currency = nf.getCurrency(); System.out.printf("识别到货币:%s,金额:%f,Locale:%s%n", currency.getSymbol(new ULocale("ar_DZ")), number.doubleValue(), "ar_DZ"); return; } catch (Exception e) { // 未知Locale时,遍历ICU支持的所有ULocale尝试匹配 for (ULocale uLocale : ULocale.getAvailableLocales()) { try { NumberFormat localeNf = NumberFormat.getCurrencyInstance(uLocale); Number num = localeNf.parse(text); Currency curr = localeNf.getCurrency(); System.out.printf("识别到货币:%s,金额:%f,Locale:%s%n", curr.getSymbol(uLocale), num.doubleValue(), uLocale); break; } catch (Exception ex) { continue; } } } } public static void main(String[] args) { String textWithCurrency = "د.ع. 40,986.63"; extractCurrencyAmount(textWithCurrency); } }
ICU4J不仅能精准识别阿拉伯货币符号,还支持全球绝大多数官方货币,完全覆盖180种的需求,且内置优化的匹配逻辑,避免原生方案遍历的低效问题。
内容的提问来源于stack exchange,提问作者Riya
相关产品推荐
相关产品推荐

