using regex to validate input formatting in C#

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 02:25:49

问题


This is a super basic question (I am brain dead today):

How do I validate in input using regexes, to see: 1) if the input is in a certain form 2) if the input is all caps (just casting the input to caps is not feasible for this)

I want ot make sure my inputs are in the form XX_XX. Here isi what I have:

public bool IsKosher(string input)
{
    Regex r = new Regex(input);
    if(r.Matches([A-Z]_[A-Z]))
    {
        return true;
    }
    return false;     
}

Any ideas why it's not compiling?

Thank you!


回答1:


You are missing double quotes, you put parameters in wrong places, and you do not need an if statement:

public bool IsKosher(string input) {
    return Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}");
}



回答2:


Quotes? A missing closing parenthesis? Matches not returning a boolean? Swapping string parameters? All will cause your code not to compile.

Though you may want this if it is "XX_XX":

var r = new Regex("[A-Z]{2}_[A-Z]{2}");
return r.IsMatch(input);



回答3:


You have to put [A-Z]_[A-Z] between quotes like this:

if(r.Matches("[A-Z]_[A-Z]")



回答4:


  1. Quotes.
  2. Two characters on either side of the _.
  3. The Regex constructor takes the pattern; the Matches method takes the string to search.
  4. The Matches method returns a MatchCollection. IsMatch returns a boolean.

Like so:

if (Regex.IsMatch(input, "[A-Z]{2}_[A-Z]{2}")


来源:https://stackoverflow.com/questions/10709186/using-regex-to-validate-input-formatting-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!