我需要解析顶部,左侧,宽度和高度的html值
用户可以输入他想要的任何内容,但我需要禁止他输入任何不正确的值,例如“px100”等。
我需要确保他输入的字符串是这样的:
100px的
100%
-100px
-100%
其中100可以是任何数字。
我试着编写代码,但是必须要做很多检查,所以我可能会有更好的解决方案。
//checks if test_str contains symbols other than allowed
private string IsStringContainsSymbolsOtherThan(string test_str, List<char> symbols)
{
if (string.IsNullOrEmpty(test_str))
return null;
for (int i = 0; i < test_str.Length; i++)
if (!symbols.Contains(test_str[i]))
return test_str[i].ToString();
return null;
}
//should return error saying what's wrong with entered value (NOT MUCH NEEDED)
private string GetExceptionMsgFromIntegerValidating(string val)
{
if (string.IsNullOrEmpty(val))
return "Value can't be empty.";
List<char> allowed_symbols = new List<char>(new char[] { '-', 'P', 'p', 'X', 'x', '%', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string possible_bad_symbol = null;
if (!string.IsNullOrEmpty(possible_bad_symbol = IsStringContainsSymbolsOtherThan(val, allowed_symbols)))
return "Entered value contains unexcpected symbol \"" + possible_bad_symbol + "\".";
if (val.Contains("-") && !val.StartsWith("-"))
return "Negative numbers should start with minus symbol";
if (val.EndsWith("px"))
{
string test_int = val.Replace("px", "");
if (string.IsNullOrEmpty(test_int))
return "Some digit must be entered before 'px'";
//this is where I understand that I need to do checks in some other way, instead of hard coding all possible situations.
//for example, user can input "100pxpx%"
}
else if (val.EndsWith("%"))
{
}
else
return "The value entered in incorrect format";
return null;
}
答案 0 :(得分:3)
这是正则表达式的完美场景:
(?:^-[1-9]+px$)|(?:^[1-9]+px$)|(?:^-[1-9]+%$)|(?:^[1-9]+%$)|(?:^0$)
Take a look at Regex
class documentation.
注意:也许它不是最好的正则表达式,但它是关于给你一个起点。
更好的正则表达式:
0
px
结尾。px
结尾。%
结尾。%
结尾。