Finding Similar Words (like bat, cat, mat)using regular expressions with .net
In this regular expression we are going to find out Similar Words like bat, cat, mat, and rat. Just take a look at above words they all same ending "at".
Regular Expression Pattern
\b[a-zA-Z](at\b)
A description of the regular expression:
First or last character in a word
Any character in this class: [a-zA-Z]
[1]: A numbered capture group. [at\b]
at\b
at
First or last character in a word
Sucessful Matches
bat
cat
mat
Zat
rat
How It Works
This regular expression will check for first character in a word (or beginning of a word) followed by any lower case or upper case character ending with at and the End of word. Above regular expression will search for word pattern have three characters and ending with "at" which will help us to find out Similar Words like bat, cat, and mat.
ASP.NET
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Finding Similar Words (bat, cat, mat )</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>Valid Format: enter some characters</span><br />
<asp:TextBox id="txtInput" runat="server"></asp:TextBox><br />
<asp:RegularExpressionValidator Id="vldRejex" RunAt="server" ControlToValidate="txtInput" ErrorMessage="Word can not end with at or not contain three characters" ValidationExpression="\b[a-zA-Z](at\b)">
</asp:RegularExpressionValidator><br />
<asp:Button Id="btnSubmit" RunAt="server" CausesValidation="True" Text="Submit"></asp:Button>
</div>
</form>
</body>
</html>
C#.NET
//use System.Text.RegularExpressions befour using this function
public bool vldRegex(string strInput)
{
//create Regular Expression Match pattern object
Regex myRegex = new Regex("\\b[a-zA-Z](at\\b)");
//boolean variable to hold the status
bool isValid = false;
if (string.IsNullOrEmpty(strInput))
{
isValid = false;
}
else
{
isValid = myRegex.IsMatch(strInput);
}
//return the results
return isValid;
}
VB.NET
‘Imports System.Text.RegularExpressions befour using this function
Public Function vldRegex(ByVal strInput As String) As Boolean
‘create Regular Expression Match pattern object
Dim myRegex As New Regex("\b[a-zA-Z](at\b)")
‘boolean variable to hold the status
Dim isValid As Boolean = False
If strInput = "" Then
isValid = False
Else
isValid = myRegex.IsMatch(strInput)
End If
‘return the results
Return isValid
End Function





Comments
No comments yet.
Leave a comment