简体   繁体   English

正则表达式只接受字母后跟逗号

[英]Regex to accept only letters followed by comma

I need to restrict the user input to the format like "wordA,wordB,wordC,wordD,wordE...". 我需要将用户输入限制为“wordA,wordB,wordC,wordD,wordE ......”等格式。 It must start with word(not case sensitive) and end with word as well, only one comma is accepted between each word. 它必须以单词开头(不区分大小写)并以单词结尾,每个单词之间只接受一个逗号。 So it should be something like this: 所以它应该是这样的:

   Match match = Regex.Match(tbx.text, @"//expression here",
    RegexOptions.IgnoreCase);

if (match.Success)
{
    //do sth
}

Can anyone help me to solve this? 任何人都可以帮我解决这个问题吗?

Assuming the input is a list of words that allows for a single word (ie no comma) as well. 假设输入是允许单个单词(即没有逗号)的单词列表。

^[a-z]+(?:,[a-z]+)*$

Since, you're already using RegexOptions.IgnoreCase there's no need to define the class like [a-zA-Z] 因为,你已经在使用RegexOptions.IgnoreCase所以不需要像[a-zA-Z]那样定义类

Match match = Regex.Match(input, @"^[0-9-]*$");

The ^ means that the match should start at the beginning of the input, the $ that it should end at the end of the input. ^指匹配应在输入的起点开始,在$它应该在输入的结束而终止。

The * means that (only) 0 or more numbers or dashes should be there (use + instead for 1 or more). *表示(仅)0或更多数字或短划线应该在那里(使用+代替1或更多)。

Try this: 尝试这个:

^([a-zA-Z]+,?)+[a-zA-Z]$

From beginning to end, must start with a letter, possibly followed by a comma (for single word entries), and can repeat any number of times; 从头到尾,必须以一个字母开头,可能后跟一个逗号(对于单个单词条目),并且可以重复任意次; also, must end in a letter. 还必须以信件结尾。

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

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