我目前正在努力解析类似于版本的String。
到目前为止我的正则表达式v(\\d+)_(\\d+)(?:_(\\d+))?
应该符合以下格式的字符串: v 版本 _ InterimVersion _ PatchVersion 即可。我的目标是,最后一个匹配组( _ PatchVersion )是可选的。
我的问题是可选部分。一个字符串v1_00
会给我一个matcher.groupCount
的3.我本来期望一个groupCount为2.所以我想我的正则表达式是错误的,或者我无法理解matcher.groupCount
。< / p>
public static void main(final String[] args) {
final String versionString = "v1_00";
final String regex = "v(\\d+)_(\\d+)(?:_(\\d+))?";
final Matcher matcher = Pattern.compile(regex).matcher(apiVersionString);
if (matcher.matches()) {
final int version = Integer.parseInt(matcher.group(1));
final int interimVersion = Integer.parseInt(matcher.group(2));
int patchVersion = 0;
if (matcher.groupCount() == 3) {
patchVersion = Integer.parseInt(matcher.group(3));
}
// ...
}
}
答案 0 :(得分:4)
正则表达式中存在与捕获组一样多的组。如果您的模式中有3组未转义的括号,则会有matcher.group(1)
,matcher.group(2)
和matcher.group(3)
。
如果第3组不匹配,则其值为 null 。检查第3组的 null 值:
if (matcher.group(3) != null) {
patchVersion = Integer.parseInt(matcher.group(3));
}
请参阅Java online demo:
final String versionString = "v1_00";
final String regex = "v(\\d+)_(\\d+)(?:_(\\d+))?";
final Matcher matcher = Pattern.compile(regex).matcher(versionString);
if (matcher.matches()) {
final int version = Integer.parseInt(matcher.group(1));
final int interimVersion = Integer.parseInt(matcher.group(2));
int patchVersion = 0;
if (matcher.group(3) != null) {
patchVersion = Integer.parseInt(matcher.group(3));
}
System.out.println(version + " > " + interimVersion + " > " + patchVersion);
}
结果:1 > 0 > 0
。