简体   繁体   中英

Regex to accept only letters followed by comma

I need to restrict the user input to the format like "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]

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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