0

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

4 Answers 4

4

simple regex:

/[ace-z]{5}/

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

Sign up to request clarification or add additional context in comments.

Comments

1

A useful regex resource I always use is:

http://regexlib.com/

Helped me out many times.

Comments

1

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.

3 Comments

I only write an example in the Q, and I cannot write explicitly every time that I should a range of characters without several charcters in the range.
@RRR so your excluded carachter changes ? So why not generate the regex extended: [abcdefg...] programmatically excluding the needed chars ?
if I dont have any option I do that, but if I can write expression that do that for me - I prefer, when I write [abcdefgh....], I don't exhaust the possibilities of Regex object
1

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

5 Comments

Drop the commas in your regex.
@Tim Pietzcker - yeah, Thanks
its not work, Regex.isMatch return true for this string "aaaaab"!
Add a comma to your regex :) ^[ace-z]{5,}$ to allow for more than 5 characters. Then this is the best solution.
its not work, and anyway I prefer a expression that avoid insert certain charcters, not write explicitly, if it possible. thanks for the want to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.