.indexOf for multiple results

后端 未结 4 739
礼貌的吻别
礼貌的吻别 2021-01-06 03:05

Let\'s say I have a text and I want to locate the positions of each comma. The string, a shorter version, would look like this:

string s = \"A lot, of text,          


        
4条回答
  •  再見小時候
    2021-01-06 03:19

    You could use Regex.Matches(string, string) method. This will return a MatchCollection and then you could determine the Match.Index. MSDN has a good example,

    using System; using System.Text.RegularExpressions;

    public class Example
    {
       public static void Main()
       {
          string pattern = @"\b\w+es\b";
          string sentence = "Who writes these notes?";
    
          foreach (Match match in Regex.Matches(sentence, pattern))
             Console.WriteLine("Found '{0}' at position {1}", 
                               match.Value, match.Index);
       }
    }
    // The example displays the following output:
    //       Found 'writes' at position 4
    //       Found 'notes' at position 17
    

提交回复
热议问题