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# 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

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.
CLOSE