quinta-feira, 16 de maio de 2013

How to identify slash asterisk using C# and Regex


This is very very annoyin. It took me a lot of time to figure out how to identify /* and */.
The code bellow do the following: it find the occurrences of /* and */

==============================================================
Method 1
        //Get all left slashs with asterisk.
         public static ArrayList getAllMatches(string pText)
        {
            ArrayList arrMatches = new ArrayList();
            string stringToTest = pText;
            const string patternToMatch = @"/\*";
            Regex regex = new Regex(patternToMatch, RegexOptions.Compiled);
            MatchCollection matches = regex.Matches(stringToTest);
            foreach (Match match in matches)
            {
                arrMatches.Add(match.Index);
            }
            return arrMatches;
      }

=================================================================
Method 2
        //Get all right slashs with asterisk.
         public static ArrayList getAllMatches(string pText)
        {
            ArrayList arrMatches = new ArrayList();
            string stringToTest = pText;
            const string patternToMatch = @"\*/";
            Regex regex = new Regex(patternToMatch, RegexOptions.Compiled);
            MatchCollection matches = regex.Matches(stringToTest);
            foreach (Match match in matches)
            {
                arrMatches.Add(match.Index);
            }
            return arrMatches;
      }

I hope it is useful for you folks.

Nenhum comentário:

Postar um comentário