.net - 限制数字字符数的正则表达式是什么?

标签 .net regex expresso

无法解决正则表达式问题。

我们正在寻找 2 个数字,然后是连字符或空格,然后是 6 个数字。必须只有 6 个数字,因此字母字符或一些标点符号或空格必须跟在 6 个数字之后或者 6 个数字必须在字符串的末尾。

其他数字也可以出现在字符串的其他地方,只要它们是分开的。

因此,这些应该匹配:

foo 12-123456 bar  
12-123456 bar  
foo 12-123456  
foo12-123456bar  
12-123456bar  
foo12-123456  
12-123456bar 99
foo12-123456 99 

这些不应该匹配:

123-12345 bar  
foo 12-1234567  
123-12345bar  
foo12-1234567  

这是我们使用的:

\D\d{2}[-|/\]\d{6}\D

Expresso 中这很好。

但在我们的 .net 应用程序中实际运行时,此模式无法匹配 6 个数字位于字符串末尾的示例。

试过这个:

\D\d{2}[-|/\]\d{6}[\D|$]

还是不匹配

foo 12-123456

最佳答案

我会重申你的模式

Must be only 6 numbers, so either an alpha character or some punctuation or space must follow the 6 numbers or the 6 numbers must be at the end of the string.

Must be only 6 numbers, so there must not be a number after the sixth number

然后使用否定前瞻断言来表达这一点。类似地,在模式的开头使用否定后视断言 来说明前两位数字之前的任何内容都不是数字。一起:

var regex = new Regex(@"(?<!\d)\d{2}[- ]\d{6}(?!\d)");

var testCases = new[]
                    {
                        "foo 12-123456 bar",
                        "12-123456 bar",
                        "foo 12-123456",
                        "foo12-123456bar",
                        "12-123456bar",
                        "foo12-123456",
                        "123-12345 bar",
                        "foo 12-1234567",
                        "123-12345bar",
                        "foo12-1234567",
                    };

foreach (var testCase in testCases)
{
    Console.WriteLine("{0} {1}", regex.IsMatch(testCase), testCase);
}

这会根据需要生成六个 True,然后生成四个 False

断言 (?<!\d)(?!\d) 分别表示“这里之前没有数字”和“这里之后没有数字”。

关于.net - 限制数字字符数的正则表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814441/

相关文章:

c# - 在 MVVM 中,ViewModel 或 Model 应该实现 INotifyPropertyChanged 吗?

.NET 6 如何添加Web服务引用

c# - 除去除数字外的所有内容的正则表达式是什么?

python - 将数字与字母分开的正则表达式

node.js - 如何使用 expresso 显示代码覆盖率输出?

c# - Visual Studio Express 2013 中的代码契约(Contract)支持

c# - 代码分析提示对象可以被处置不止一次。为什么?

用于在字符串中搜索的 Java 正则表达式

android - 在检测单元测试中模拟方法

c# - 如何进行平衡组捕获?