我不确定如何用正则表达式来实现这一点(或者我是否能够;我对正则表达式很新)。我有一个角度值,用户将输入并尝试验证该条目。它采用度-分-秒的形式。我遇到的问题是,如果用户错误地输入了秒部分,我必须捕获该错误,但我的度-分匹配是成功的。
也许方法会更好地解释:
也许方法会更好地解释:
private Boolean isTextValid(String _angleValue) {
Regex _degreeMatchPattern = new Regex("0*[1-9]");
Regex degreeMinMatchPattern = new Regex("(0*[0-9]-{1}0*[0-9]){1}");
Regex degreeMinSecMatchPattern = new Regex("0*[0-9]-{1}0*[0-9]-{1}0*[0-9]");
Match _degreeMatch, _degreeMinMatch, _degreeMinSecMatch;
_degreeMinSecMatch = degreeMinSecMatchPattern.Match(_angleValue);
if (_degreeMinSecMatch.Success)
return true;
_degreeMinMatch = degreeMinMatchPattern.Match(_angleValue);
if (_degreeMinMatch.Success)
return true;
_degreeMatch = _degreeMatchPattern.Match(_angleValue);
if (_degreeMatch.Success)
return true;
return false;
}
}
我想检查度分格式是否匹配,但只有当用户没有输入任何秒数数据时才这样做。我可以通过正则表达式来实现吗,还是需要解析该字符串并单独评估每个部分?谢谢。
编辑:正确的数据示例为45-23-10。问题在于45-23也是有效数据;0秒被理解为空缺。因此,如果用户意外输入了45-23-1=,我的代码中的degreeMinMatchPattern正则表达式将成功匹配,即使它是无效的。
第二次编辑:只要注意到分钟和秒钟是可选的。用户输入45也是有效的。