Jan 29 2011

Search Multiple Strings Using Regular Expression

Category: .net,CodeProject,TipsJebarson Jebamony @ 11:10 pm

This is small piece of code snippet which I wanted to share as we face this necessity in our day to day programming. Suppose you have a need when you need to search multiple string, say you need to search strings like “int”, “float”, “string” in a piece of text. Below is how you will achieve it without using any loop and in a simple and straight forward way.

string pattern = "int|float|string";
MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);

Since the return value is a “MatchCollection”, you can find the index of the matched string and many other properties / methods supported by “Match” type.


4 Responses to “Search Multiple Strings Using Regular Expression”

  1. BTW says:

    And it gets even better if you include b inside your regex:
    string pattern = @"bintb|bfloatb|bstringb";

    That way you'd match whole words only, other "int" would match "into" or "paint".

    Notice the nice use of the @ strings, which avoids the need to escape the characters.

  2. Edward says:

    Hi there,I found your articles' quality are good,I suggest you to submit links of your article to our website http://www.webmasterclip.com which is a social bookmarking website for webmasters ,web designers,web developers. You will get more traffic and backlinks.Submitting a link to WebmasterClip is as easy as Digg,just need 0.5-1.5 minutes.

  3. jebarson says:

    @BTW thanks for your comment. Yeah I agree with you.

  4. Microsoft Programmers » Guide: Write Your Own Syntax Highlighter says:

    […] be searching for multiple strings on a single statement using regular expression. Check out “Search Multiple Strings Using Regular Expression“. Also in our sample, we make the highlighting on every text change for the entire text which […]

Leave a Reply