java - 将文件中的所有数字解析为 BigDecimal Java

标签 java regex numbers

我想将输入中的所有数字添加到集合中并对它们进行排序。

我有这样的输入文件:

12i -+3456i
78,i910 
11
i-12i


13.14r
15.r16r
i17.18

-+19.20
+r21.22
+23.242526r

+-27.28r
-29.30r
-.313233r
r-0.343536rr


r.34r
3536.r
r+37.38

Liczba -0.1234 jest mniejsza niz liczba .2 i wieksza niz liczba -1;

i123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789i

当然还有整数、 double 、大整数等。我想将它们放入集合并排序。如果我通过这个输入 3 次,这并不难:

1. Create regex for integers and filter the input add those integers into collection
2.  Create regex for doubles and filter the input add those doubles into collection
3.  Create regex for bigIntegers and filter the input add those bigIntegers into collection
4.Sort this collection of BigDecimals.

但这似乎很愚蠢。 有没有办法一次性将所有这些数字放入输入集合中?使用正则表达式。

编辑:

12,12 == 12.12 --> double
12i --> i does not count this is integer 12

编辑2: 正确的输出顺序

-29.30
-27.28
-12
-1
-0.343536
-0.313233
-0.1234
0.2
0.34
11
12
13.14
15
16
17.18
19.20
21.22
23.242526
37.38
78
910
3456
3536
123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789

最佳答案

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
} 

为您提供所有正则表达式匹配的ArrayList。如果我了解 Java,我可能会向您展示如何将其更改为 BigDecimals 的 ArrayList,但我想您可以自己做到这一点。然后排序即可。

说明:

-?          # Match an optional minus sign.
(?:         # Either match:
 \d+        # a number,
 (?:\.\d+)? # optionally followed by a decimal part
|           # or
 \.\d+      # just a decimal part
)           # End of alternation

请访问 regex101 查看实际情况。 .

(编辑:新版本不会产生大量空匹配(旧版本也匹配空字符串)

关于java - 将文件中的所有数字解析为 BigDecimal Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14343551/

相关文章:

java - SQL 查询抛出异常

regex - Powershell - 如何用字符串中的变量替换数字?

java - Java中仅从偶数创建新数组的方法

java - 获取范围 (x, y) 内的随机 BigInteger

java - 我可以使用 JDialog 来实现此目的吗?

java - 将 SimpleStringProperty 转换为字符串?

python - 正则表达式:扑克牌解析器,N of a kind

php - 如何解析这个 OFX 文件?

c++ - 如何确保在 Windows 10 上将数字呈现为阿拉伯数字?

java - Java 中的整数