Search Multiple Strings Using Regular Expression

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.


Search Multiple Strings Using Regular Expression

4 thoughts on “Search Multiple Strings Using Regular Expression

  1. 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. Hi there,I found your articles' quality are good,I suggest you to submit links of your article to our website 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.

Leave a Reply

Scroll to top
%d bloggers like this: