Bit2Dev
Bit2Dev

Reputation: 57

Combine 2 or more regex in 1

I've 2 regular expression:

  1. string regex1 = "(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)"; this will check for 'admin' substring in the given string and case is insensitive.

  2. string regex2 = "^[^<>?]{5,100}$"; this will check for special char(^<>?) and length between 5 to 100 only.

I want a regular expression where both the regex can be validated at once with the use of only single regex.

Ex-

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
    ControlToValidate="txtBox1" ErrorMessage="Validation Failed!"
    ValidationExpression="(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)">
</asp:RegularExpressionValidator>

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
    ControlToValidate="txtBox2" ErrorMessage="Length Validation Failed!"
    ValidationExpression="^[^<>?]{5,100}$">
</asp:RegularExpressionValidator>

Q. Can we have a single "RegularExpressionValidator" that serves both the above functionality?

Upvotes: 1

Views: 109

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

The (?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$) regex is too redundant, it is equal to (?i)^(?!^.*?admin).*$. It basically matches any string that contains no admin substring.

The ^[^<>?]{5,100}$ regex disallows <, > and ? in the string and sets string length limit.

Combining the two is done by replacing the .* in the first pattern with the consuming part of the second regex ([^<>?]{5,100}):

(?i)^(?!^.*?admin)[^<>?]{5,100}$

Details

  • (?i) - case insensitive mode on
  • ^ - start of string
  • (?!^.*?admin) - no admin substring allowed anywhere after 0 or more chars other than line break chars, as few as possible
  • [^<>?]{5,100} - five to a hundred chars other than <, > and ?
  • $ - end of string.

Upvotes: 1

Related Questions