Match at every second occurrence

前端 未结 6 1625
我在风中等你
我在风中等你 2020-11-28 07:40

Is there a way to specify a regular expression to match every 2nd occurrence of a pattern in a string?

Examples

  • searching for a agains
6条回答
  •  不知归路
    2020-11-28 08:08

    If you're using C#, you can either get all the matches at once (i.e. use Regex.Matches(), which returns a MatchCollection, and check the index of the item: index % 2 != 0).

    If you want to find the occurrence to replace it, use one of the overloads of Regex.Replace() that uses a MatchEvaluator (e.g. Regex.Replace(String, String, MatchEvaluator). Here's the code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string input = "abcdabcd";
    
                // Replace *second* a with m
    
                string replacedString = Regex.Replace(
                    input,
                    "a",
                    new SecondOccuranceFinder("m").MatchEvaluator);
    
                Console.WriteLine(replacedString);
                Console.Read();
    
            }
    
            class SecondOccuranceFinder
            {
                public SecondOccuranceFinder(string replaceWith)
                {
                    _replaceWith = replaceWith;
                    _matchEvaluator = new MatchEvaluator(IsSecondOccurance);
                }
    
                private string _replaceWith;
    
                private MatchEvaluator _matchEvaluator;
                public MatchEvaluator MatchEvaluator
                {
                    get
                    {
                        return _matchEvaluator;
                    }
                }
    
                private int _matchIndex;
                public string IsSecondOccurance(Match m)
                {
                    _matchIndex++;
                    if (_matchIndex % 2 == 0)
                        return _replaceWith;
                    else
                        return m.Value;
                }
            }
        }
    }
    

提交回复
热议问题