chris
chris

Reputation: 63

Regex Negative Lookahead

I have a situation wherein I need to search through a VS project for any control that does not have a MaxLength property defined.

For example:

<asp:TextBox ID="txtName" runat="server" MaxLength="50" Text="Enter Name" />
<asp:TextBox ID="txtOther" MaxLength="25" runat="server" />
<asp:TextBox ID="MaxLength" runat="server" />
<asp:TextBox ID="txtMisc" runat="server" Width="100" />

Does anyone have a suggestion for a regular expression pattern that will find the controls that do not have a MaxLength defined?

My first attempt at this, which seems to work, seems imperfect at best...

<asp:TextBox.*?M(?!axLength=).*?/>

I would love to see a better solution.

Note: the Visual Studio search chokes on my pattern above. I was forced to use a different application to actually search using this pattern

Upvotes: 3

Views: 1057

Answers (2)

Alan Moore
Alan Moore

Reputation: 75222

I think this is what you were trying for:

<asp:TextBox(?:(?!MaxLength=|>).)*/>

The . consumes one character at a time, but only after the lookahead has determined that it's not > or the beginning of MaxLength=. Note that you must exclude > in the lookahead, or it will keep looking for MaxLength= beyond the end of the current element. For example, when applied to

<asp:TextBox ID="txtMisc" /><asp:TextBox MaxLength="50" />

...you want it to match the first tag, but it doesn't because the lookahead sees MaxLength= in the second element. A non-greedy quantifier like .*? will not prevent that from happening. It might seem like it's working correctly, but that's only because the tags usually appear on separate lines, and the . doesn't match newlines.

The Visual Studio version would be:

\<asp\:TextBox(~(MaxLength=|\>).)*/\>

<, > and : all have special meanings in VS regexes and have to be escaped, and ~(...) is the VS syntax for a negative lookahead.

Upvotes: 5

Tom
Tom

Reputation: 39

Try this... negative lookahead on "MaxLength" within the element

\<(?!.*MaxLength[^/>]*)[^/>]*/\>

Upvotes: 1

Related Questions