开发者

Regular Expression in .NET

I should write a regex pattern in c# that checks for input string whether it conains certain characters and does not conain another characters, for example: I want that the string contain only a-z, not co开发者_如何学Cntain (d,b) and the length of all the string longer than 5, I write "[a-z]{5,}", how can I avoid that the input contain d and b?

Additional question: Can I have option to condition in the regex, in other words if whichever boolian var equals true check somthing and if it equals false not check it?

Thanks


simple regex:

/[ace-z]{5}/

matches five occurrences of: characters 'a', 'c', or any character between 'e' and 'z'.


A useful regex resource I always use is:

http://regexlib.com/

Helped me out many times.


For the first question, why not simply try this: [ace-z]{5,} ? For the second option, can't you format the regex string in some way based on the boolean variable before executing it ? Or, if you want programmatically exclude some chars, you can create programmatically the regex by expliciting all the chars [abcdefgh....] without the exclusion.


if you want to skip d and b

[ace-z]{5,}

And yes you can have a boolean check using isMatch method of Regex class

 Regex regex = new Regex("^[ace-z]{5,}$");
    if (regex.IsMatch(textBox1.Text))
    {
        errorProvider1.SetError(textBox1, String.Empty);
    }
    else
    {
        errorProvider1.SetError(textBox1, 
              "Invalid entry");
    }

Source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜