简体   繁体   English

RegEx for string以数字开头,后跟字母

[英]RegEx for string starts with numbers and followed by letters

I want Regular expression for such inputs. 我想要这种输入的正则表达式。

1
1a
1b
1c
1d
2
2a
2b
2c

But if i write following inputs then it should not allow. 但如果我写下以下输入,那么它不应该允许。

a
b
c

The string must start with 1 or 2 (only once and mandatory) and then followed by any character between a to z(only once) 字符串必须以1或2开头(仅一次和必填),然后是a到z之间的任何字符(仅一次)

So total string length is 2 only 因此总字符串长度仅为2

the first letter will be always 1 or 2 (first letter is mandatory) 第一个字母将始终为1或2(首字母为必填项)
second letter will be a to z (not mandatory) 第二个字母是a到z(不是强制性的)

I tried this [1-2]?[a-zA-Z]? 我试过这个[1-2]?[a-zA-Z]? but it allow me to enter string starts with any character.. 但它允许我输入任何字符的字符串开头..

I want this RegEx for C#.Net 我希望这个RegEx用于C#.Net

You need to anchor the regular expression - you need to specify that they need to be at the start of the string. 您需要锚定正则表达式 - 您需要指定它们需要位于字符串的开头。

You also need to specify that 1 or 2 has to be there. 您还需要指定1或2 必须在那里。 There are several ways to do so, I chose alternation (1|2) , thought the character class is another option ( [12] ). 有几种方法可以做到,我选择了交替(1|2) ,认为字符类是另一种选择( [12] )。

You do that by starting the regex with ^ : 你通过使用^启动正则表达式来做到这一点:

^(1|2)[a-zA-Z]?

So, the above will match 所以,上面会匹配

这样做^(1|2)[a-zA-Z]?$

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

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