简体   繁体   English

用于检查在文本框中输入的文本是否包含数字,逗号和连字符的正则表达式

[英]Regular expression to check if the text entered in a textbox has numbers, commas and hyphens

I have created a windows form, that has 2 columns of textboxes - Range of lines and Total number of lines. 我创建了一个Windows窗体,该窗体具有2列文本框-行数范围和总行数。 I want to have a check in the Range of lines textboxes to make sure that the data entered consists only of numbers, commas and hyphens in the correct format - that is, it can be something like : 10-20,30-40,50,60,70. 我想在“行数范围”文本框中进行检查,以确保输入的数据仅包含数字,逗号和连字符,且格式正确-即,它可以是:10-20,30-40,50 60,70年代。 But anything apart from this should not be allowed. 但是,除此以外的任何内容都不允许。

Basically I want to automatically fill up the "Total number of Lines" textbox with the data available in the "Range of lines" textbox. 基本上,我想用“行数范围”文本框中的可用数据自动填充“行数总数”文本框。 So in the above example, the count would be - (20 minus 10) + (40 minus 30) plus 1(for line 50) plus 1(for line 60) plus 1(for line 70) = 23. 因此在上面的示例中,计数为-(20减去10)+(40减去30)加1(对于第50行)加1(对于第60行)加1(对于第70行)= 23。

I tried something like : 我尝试了类似的东西:

string reg = @"^([0-9]+([,][0-9]+))* |([0-9]+([.\–-][0-9]+))$";

But this validates a case like 10-20-30 also as correct. 但这可以验证类似10-20-30的情况也是正确的。 Which is not right according to my expecation. 根据我的期望,这是不对的。

Could you please help me here. 您能在这里帮我吗? Many thanks in advance. 提前谢谢了。

The possible formats for each component are: 每个组件的可能格式为:

\d+-\d+
\d+

We can combine them since they share the same structure: 我们可以合并它们,因为它们具有相同的结构:

\d+(-\d+)?

The usual regex pattern for several things X that are separated by a separator is 用分隔符分隔的几件事X的常规正则表达式模式是

X(,X)*

So from that we can build the final regex that has at least one of those components, separated by commas: 因此,我们可以构建最终的正则表达式,其中至少包含这些组件之一,并用逗号分隔:

^\d+(-\d+)?(,\d+(-\d+)?)*$

Quick PowerShell test: 快速PowerShell测试:

PS> '50,60','10-20','1,2-5,7','10-20,30-40,50,60,70','10-20-30' -match '^\d+(-\d+)?(,\d+(-\d+)?)*$'
50,60
10-20
1,2-5,7
10-20,30-40,50,60,70

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM