如何过滤掉某些组合?

问题描述 投票:1回答:1

我正在尝试使用Regex过滤TextBox的输入。我需要在小数点前最多3个数字,然后我需要2个数字。这可以是任何形式。

我已经尝试更改正则表达式命令,但它会产生错误,单个输入将无效。我在WPF中使用TextBox来收集数据。

bool containsLetter = Regex.IsMatch(units.Text, "^[0-9]{1,3}([.] [0-9] {1,3})?$");
if (containsLetter == true)
{
    MessageBox.Show("error");
}
return containsLetter;

我希望正则表达式过滤器接受这些类型的输入:

111.11,
11.11,
1.11,
1.01,
100,
10,
1,
c# regex wpf filter
1个回答
1
投票

正如在注释中提到的那样,空格是将在您的正则表达式模式中按字面解释的字符。

因此,在你的正则表达式的这一部分:

([.] [0-9] {1,3})

  • 预计.[0-9]之间的空间,
  • [0-9]之后,正则表达式将13空间相匹配。

这就是说,出于可读性目的,您可以通过多种方式构建正则表达式。

1)将评论从正则表达式中删除:

string myregex = @"\s" // Match any whitespace once
+ @"\n"  // Match one newline character
+ @"[a-zA-Z]";  // Match any letter

2)使用语法(?#comment)在正则表达式中添加注释

needle(?# this will find a needle)

Example

3)在你的正则表达式中激活自由间隔模式:

nee # this will find a nee...
dle # ...dle (the split means nothing when white-space is ignored)

doc:https://www.regular-expressions.info/freespacing.html

Example

© www.soinside.com 2019 - 2024. All rights reserved.