ASP.NET offers strong support for regular expressions in the System.Text.RegularExpressions Namespace. This is great since regular expressions are essential if you want to do anything beyond basic text manipulations and searches.
You can read more about regular expression support in ASP.NET on the official MSDN page. The MSDN site also includes a few good getting started examples if you are interested.
Recently I found myself facing an interesting task: I was building a simple search form which consisted of a text area and submit button on a Web page. The desired behavior was as follows:
- Users could enter a partial term into the text area and then click the submit button to search for that partial text match.
- The codebehind would search through an MS SQL Server database to find the partial matches
- The codebehind would render the search results into a GridView control with the partial match text highlighted with a yellow background color
In theory putting this together is quite simple. The catch was figuring out how to highlight the partial text that the user searched for in the database results without changing the capitalization or other formatting.
For example if the user searched for the term EXAMPLe TexT (notice the crazy capitalization), then the data results should highlight the correct results in the search result output using the capitalization/formatting found in the database. Or more simply: the results should not depend on the user-entered search term, but should show the original text from the database surrounded by HTML markup tags. So no matter what strange capitalization the user entered, the search results should be properly capitalized and highlighted.
Continue reading “Regular Expressions in .NET to Surround but not Replace Text Matches”