RRR
RRR

Reputation: 4175

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 contain (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

Upvotes: 0

Views: 366

Answers (4)

niksvp
niksvp

Reputation: 5563

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

Upvotes: 1

Felice Pollano
Felice Pollano

Reputation: 33272

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.

Upvotes: 1

WraithNath
WraithNath

Reputation: 18013

A useful regex resource I always use is:

http://regexlib.com/

Helped me out many times.

Upvotes: 1

Spudley
Spudley

Reputation: 168803

simple regex:

/[ace-z]{5}/

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

Upvotes: 4

Related Questions