gpt4 book ai didi

java - Reg~x 代表 N~number

转载 作者:搜寻专家 更新时间:2023-11-01 01:11:37 25 4
gpt4 key购买 nike

感谢您的帮助。

什么是优雅的正则表达式来检查一个字符串是否包含一个数字?有什么建议么?谢谢。

最佳答案

我不认为异常(即使它被触发)比正则表达式昂贵得多 - 您必须分析它并查看它是否真的有所作为。

也就是说,一个根据 Java Docs 实现 BigDecimal 语法的正则表达式是

[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?

解释:

[+-]?       # 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

如果您想允许不同的数字格式(和千位分隔符),您可以先从 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);

然后,您可以在将数字移交给 BigDecimal 转换之前将与区域设置相关的位替换回美国对应位,如果这不是区域设置感知的话。

关于java - Reg~x 代表 N~number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4049340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com