我不认为异常(即使它被触发)比正则表达式贵得多 - 你必须对它进行分析,看看它是否真的有所作为.
也就是说,根据Java Docs实现BigDecimal语法的正则表达式是
[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?
Run Code Online (Sandbox Code Playgroud)
说明:
[+-]? # optional sign
(?: # required significand: either...
\d+ # a number
(?:\.\d*)? # optionally followed by a dot, optionally followed by more digits
| # or...
\.\d+ # just a dot, followed by digits (in this case required)
) # end of significand
(?: # optional exponent
[eE] # required exponent indicator
[+-]? # optional sign
\d+ # required digits
)? # end of exponent
Run Code Online (Sandbox Code Playgroud)
如果您想允许不同的数字格式(以及数千个分隔符),您可以先从中获取这些值DecimalFormatSymbols并使用它构建正则表达式.
像这样的东西(我不懂Java,所以随意纠正我的语法错误):
// you need java.util.regex.Pattern and java.text.DecimalFormatSymbols
string ds = Pattern.quote(DecimalFormatSymbols.getDecimalSeparator())
string gs = Pattern.quote(DecimalFormatSymbols.getGroupingSeparator())
string ms = Pattern.quote(DecimalFormatSymbols.getMinusSign())
string es = Pattern.quote(DecimalFormatSymbols.getExponentSeparator())
string myre =
"(?xi)\n # verbose, case-insensitive regex" +
"[+" +ms+ "]? # optional sign\n" +
"(?: # required significand: either...\n" +
" (?:\\d{1,3}(?:" +gs+ "\\d{3}|\\d++) # a number with optional thousand separators,\n" +
" (?:" +ds+ "\\d*)? # optionally followed by a dot, optionally followed by more digits\n" +
" | # or...\n" +
ds+ "\\d+ # just a dot, followed by digits (in this case required)\n" +
") # end of significand\n" +
"(?: # optional exponent\n" +
es+ " # required exponent indicator\n" +
" [+" +ms+ "]? # optional sign\n" +
" \\d+ # required digits\n" +
")? # end of exponent"
boolean foundMatch = subjectString.matches(myregex);
Run Code Online (Sandbox Code Playgroud)
然后,在将数字转换为BigDecimal转换之前,您可以将依赖于区域设置的位替换回其美国对应位,如果这不是区域设置感知的话.