我接受来自用户输入的字符串,并试图确定它是否与regex匹配。如果是这样的话,我需要从输入中提取出某些匹配的组并对它们进行处理。
有效字符串必须具有以下形式:
-")%")有效字符串输入的示例:
我最好的尝试:
String numRange = getFromUser();
Pattern pattern = Pattern.compile("([0-9]{1,2}\.[0-9]{1,2})-([0-9]{1,2}\.[0-9]{1,2})[%]*");
Matcher matcher = pattern.matcher(numRange);
if (matcher.matches()) {
String lowRangeVal = matcher.group(1);
String highRangeVal = matcher.group(2);
// continue processing here
}不管用。有人能发现我哪里出问题了吗?
发布于 2022-01-07 00:31:05
我修改了您的模式,以满足您的要求如下。
([0-9]{1,2}(\.[0-9]{1,2})*)-([0-9]{1,2}(\.[0-9]{1,2})*)[%]*我只在小数位和第二个数字部分中添加了可选的(*)。我假设小数位之前或之后的数字被限制在长度1到2,尽管你没有这么说。
发布于 2022-01-07 00:49:10
使用
Pattern pattern = Pattern.compile("(\\d+(?:\\.\\d+)?)-(\\d+(?:\\.\\d+)?)%*");见正则证明。
解释
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
%* '%' (0 or more times (matching the most
amount possible))https://stackoverflow.com/questions/70615198
复制相似问题