我正在创建WPF TextBox扩展控件,它必须仅使用正则表达式允许以下输入:
我很难找出允许通过该范围的正则表达式。我开始时:
^[0-9]*(?:\.[0-9]*)?$
但它并不符合我的要求。所以我要求帮助才能得到这个正则表达式。
答案 0 :(得分:4)
尝试这种模式:
^24(?:\\.00?)?|(?:2[0-3]|1?[0-9])(?:\\.[0-9]{1,2})?$
答案 1 :(得分:4)
为什么你想使用正则表达式让人头痛?只需解析文本,检查值的范围和小数位数:
bool IsValid(string text) {
decimal candidate;
if(decimal.TryParse(text, out candidate)){
if(
candidate >= 0 && // Check lower bound
candidate <= 24 && // CHeck higher bound
Math.Round(candidate, 2) == candidate // Check number of decimals
) {
return true;
}
}
return false;
}
此外,您将通过让系统处理此问题来避免全球化问题(使用.
,,
,具体取决于文化)。