articles » current » dot-net » find-keywords-in-text-using-regex

.NET: Find Keywords in Text using Regex

How to find a keyword in text using C# Regular Expressions

See related: Strip HTML 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";
Regex regex1 = new Regex(@"(?i)\b" + Regex.Escape(keyword1) + @"\b");
Regex regex2 = new Regex(@"(?i)\b" + 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 = Regex.Replace(keyword, @"[^0-9a-zA-Z]+", string.Empty) // remove all special characters from a keyword
Regex regex = new Regex(@"(?i)\b" + keyword + @"\b");
bool found = regex.Match(text).Success; // true

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.