gpt4 book ai didi

Java 正则表达式 - 提取字符串中特定单元之前的所有 float

转载 作者:行者123 更新时间:2023-11-29 04:35:43 25 4
gpt4 key购买 nike

我是 Java 正则表达式的新手。我想知道如何在 % 之前提取数字或 float .例如:

"Titi 10% Toto and tutu equals 20X"
"Titi 10.50% Toto and tutu equals 20X"
"Titi 10-10.50% Toto and tutu equals 20X
"Titi 10sd50 % Toto and tutu equals 20X
"Titi 10-10.50% or 10sd50 % Toto and tutu equals 20X

输出:

10
10.50
10-10.50
10sd50
10-10.50;10sd50

我的想法是将"space + number(% or space%)"前后全部替换掉通过 ;为了提取 % 之前的所有值或组值.我尝试使用它:replaceAll("[^0-9.]+|\\.(?!\\d)(?!\\b)\\%",";"); = 没有成功

我该怎么做?

最佳答案

这个应该做的工作:

((?:\d+(?:+|-|sd))?\d+(?:\.\d+)\h*%)

解释:

(               : start group 1
(?: : start non capture group
\d+ : 1 or more digits
(?:+|-|sd) : non capture group that contains + or - or sd
)? : end group
\d+ : 1 or more digits
(?: : start non capture group
\. : a dot
\d+ : 1 or more digits
) : end group
\h* : 0 or more horizontal spaces
% : character %
) : end of group 1

结果将在第 1 组中。

在 java 中你必须双重转义,为了便于阅读,我没有在这里这样做。

关于Java 正则表达式 - 提取字符串中特定单元之前的所有 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41673682/

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