Below is a code fragment I use to extract a matching string using RegEx (C# Regular Expression). I put it in a class library, and make it available to BizTalk Orchestrations, Pipeline, and Map Scripting functoids that might need to call it.

//using System.Text.RegularExpressions;  <-- put this above your class, put the method below in some class library 

        public static string extractUsingRegEx(string text, string pattern)
        {
            string resultString = "";
            Regex r1 = new Regex(pattern);
            Match match = r1.Match(text);
            if (match.Success)
            {
                resultString = match.Groups[1].Value;
            }
            else
            {
                throw new System.ApplicationException
                    ("RegEx did not match: pattern=" + pattern + " text=" + text);
            }
            return resultString;
        }

Below is an example usage of the RegEx routine

            string searchText = "LastName=Walters FirstName=Neal State=Texas";
            string pattern = "FirstName=(.*?) "; 
            string result = extractUsingRegEx(searchText, pattern);
            Console.WriteLine("Result=" + result); 

The parentheses indicate the text to be captured and returned in the result string. Note that in RegEx, the ? mark is used as the non-greedy indicator.

Tagged with:

Filed under: C#