[英]TextBox filter using Regex
I am struggling to apply a filter on a TexBox. 我正在努力在TexBox上应用过滤器。 I have 3 filter types:
我有3种过滤器类型:
1) Only Numbers (positive)
Example: 123 good, -123, ad8, 12.0 not good 1)
Only Numbers (positive)
示例:123好,-123,ad8、12.0不好
2) Only Numbers plus "^" and "." chars
2)
Only Numbers plus "^" and "." chars
Only Numbers plus "^" and "." chars
Example: 123^3, -34, -34.5 good, ad8, 23-4 not good Only Numbers plus "^" and "." chars
示例:123 ^ 3,-34,-34.5良好,ad8、23-4不好
3) Only POSITIVE Numbers plus "^" and "." chars
3)
Only POSITIVE Numbers plus "^" and "." chars
Only POSITIVE Numbers plus "^" and "." chars
Example: 123^3, 34.5 good, -34, ad8, 23-4 not good Only POSITIVE Numbers plus "^" and "." chars
示例:123 ^ 3、34.5好,-34,ad8、23-4不好
Here is my work: 这是我的工作:
private void PriceInput_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
switch (FieldType)
{
case InputFieldType.TypeQuantity:
tb.Text = KeyFilter.ExtractNumbersOnly(tb.Text);
break;
case InputFieldType.TypePositivePrice:
tb.Text = KeyFilter.ExtractPositivePricesOnly(tb.Text);
break;
case InputFieldType.TypePrice:
tb.Text = KeyFilter.ExtractPricesOnly(tb.Text);
break;
}
}
and KeyFilter: 和KeyFilter:
public static string ExtractNumbersOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "\\d+");
return match.Value;
}
public static string ExtractPricesOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "^[-]?\\d+([.]\\d+)?$");
return match.Value;
}
public static string ExtractPositivePricesOnly(string s)
{
Match match = System.Text.RegularExpressions.Regex.Match(s, "^[+]?\\d+([.]\\d+)?$");
return match.Value;
}
(1) (1)
^\\d+$
(2) (2)
^-?\\d+(\\.\\d+)?(\\^)?(-?\\d+(\\.\\d+)?)?$
(3) actually easier than (2). (3)实际上比(2)容易。 Just take (2) and remove the negative signs.
只需取(2)并消除负号。
^\\d+(\\.\\d+)?(\\^\\d+(\\.\\d+)?)?$
The required three regex are sequentially(as you asked) at below: 所需的三个正则表达式依次(如下所示)在以下位置:
^\\d+$
^-?\\d+[.^]\\d+$
^\\d+[.^]\\d+$
Please escape the \\
with your escape character in C#
请使用
C#
转义符对\\
进行转义
Regex.IsMatch("123", "^\\d+$")
Regex.IsMatch("-123^33", "^-?\\d+((\\^\\d+)|(\\.\\d+))?$")
Regex.IsMatch("123^33", "^\\d+((\\^\\d+)|(\\.\\d+))?$")
Note that 2nd and 3rd does NOT work if ^
and .
请注意,如果
^
和,则2nd和3rd无效.
both are included, eg 123.44^2 <- as per given RegEx, this is NOT a correct input 两者都包括在内,例如123.44 ^ 2 <-根据给定的RegEx,这不是正确的输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.