PROWAREtech








.NET: Find Keywords in Text using Regex
How to find a keyword in text using C# and regular expressions.
See related: Strip HTML Tags from HTML Text and strip SCRIPT tags from HTML text
Regular expressions make is simple work to find keywords in text.
string text = "this is a test!";
string keyword1 = "test";
string keyword2 = "tes";
var regex1 = new System.Text.RegularExpressions.Regex(@"(?i)\b" + System.Text.RegularExpressions.Regex.Escape(keyword1) + @"\b");
var regex2 = new System.Text.RegularExpressions.Regex(@"(?i)\b" + System.Text.RegularExpressions.Regex.Escape(keyword2) + @"\b");
bool found1 = regex1.Match(text).Success; // true
bool found2 = regex2.Match(text).Success; // false
Use Regex to remove special characters in a keyword.
string text = "this is a C++ test!";
string keyword = "c++";
keyword = System.Text.RegularExpressions.Regex.Replace(keyword, @"[^0-9a-zA-Z]+", string.Empty) // remove all special characters from a keyword
var regex = new System.Text.RegularExpressions.Regex(@"(?i)\b" + keyword + @"\b");
bool found = regex.Match(text).Success; // true