ASP.NET Find Words Not Preceded by Other Words

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This recipe finds a word likely in text but will skip over it if the word before it is not. It provides an example of how to use a negative look-behind.

[edit] code

<%@ Page Language="vb" AutoEventWireup="false" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head><title></title>
</head>
<body>
<form Id="Form1" RunAt="server">
    <asp:TextBox id="txtInput" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator Id="revInput" RunAt="server"
    ControlToValidate="txtInput"
    ErrorMessage="Please enter a valid value"
    ValidationExpression=".*(?<!not\s+)likely\b.*">
    </asp:RegularExpressionValidator>
    <asp:Button Id="btnSubmit" RunAt="server" CausesValidation="True"
    Text="Submit"></asp:Button>
</form>
</body>
</html>

[edit] How It Works

This recipe uses a negative look-behind as it’s searching through the string to make sure what you’re looking for, likely\b, isn’t preceded by not\s+. It breaks down like this:

Regular Expression Description
(?<! the negative look-behind that matches . . .
not the characters n, o, and t, followed by . . .
\s a space . . .
+ found one or more times . . .
) the end of the look-behind . . .
likely the letters l, i, k, e, l, and y, followed by . . .
\b a word boundary character.
Personal tools