如果我们看一下这个模式,间隔要么以'['
or a '('
,然后后面至少跟一个数字,再跟一个逗号,再跟一个或多个数字,最后以任一数字结尾']'
or ')'
.
所以正则表达式将如下所示:
^[\\(|\\[](\\d+),(\\d+)[\\)|\\]]$
这里是分解的:
^
[\\(|\\[] -> start either with `'['` or `'('` (we need to escape the special characters with `\\`)
(\\d+) -> followed by one or more digit that we capture in a group
, -> followed by a comma
(\\d+) -> followed again by one or more digit that we capture in another group
[\\)|\\]] -> and that finishes either with `']'` or `')'`
$
^
and $
断言所有字符串都与表达式匹配,而不仅仅是其中的一部分。
所以我们有了正则表达式,耶!
现在我们需要创建一个Pattern
从中获取实例,以便能够从中获取匹配器。最后我们检查字符串是否与模式匹配并获取相应的组
Pattern p = Pattern.compile("^[\\(|\\[](\\d+),(\\d+)[\\)|\\]]$");
Matcher m = p.matcher("(0,100)");
if(matcher.matches()) {
int lowerBound = Integer.parseInt(matcher.group(1));
int upperBound = Integer.parseInt(matcher.group(2));
System.out.println(lowerBound + "_" + upperBound);
}
以下输出0_100
.
现在是最后一步,获取第一个和最后一个字符并从中创建适当的范围;把它们放在一起:
class RangeFactory {
private static final Pattern p = Pattern.compile("^[\\(|\\[](\\d+),(\\d+)[\\)|\\]]$");
public static Range from(String range) {
Matcher m = p.matcher(range);
if(m.matches()) {
int length = range.length();
int lowerBound = Integer.parseInt(m.group(1));
int upperBound = Integer.parseInt(m.group(2));
if(range.charAt(0) == '(') {
if(range.charAt(length - 1) == ')') {
return Range.open(lowerBound, upperBound);
}
return Range.openClosed(lowerBound, upperBound);
} else {
if(range.charAt(length - 1) == ')') {
return Range.closedOpen(lowerBound, upperBound);
}
return Range.closed(lowerBound, upperBound);
}
}
throw new IllegalArgumentException("Range " + range + " is not valid.");
}
}
这是一些测试用例:
List<String> ranges =
Arrays.asList("(0,100)", "[0,100]", "[0,100)", "(0,100]", "", "()", "(0,100", "[,100]", "[100]");
for(String range : ranges) {
try {
System.out.println(RangeFactory.from(range));
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
}
其输出:
(0‥100)
[0‥100]
[0‥100)
(0‥100]
java.lang.IllegalArgumentException: Range is not valid.
java.lang.IllegalArgumentException: Range () is not valid.
java.lang.IllegalArgumentException: Range (0,100 is not valid.
java.lang.IllegalArgumentException: Range [,100] is not valid.
java.lang.IllegalArgumentException: Range [100] is not valid.
您可以改进正则表达式(以接受无限边界的范围等),但它应该为您提供一个良好的起点。
希望能帮助到你! :)