Jeśli używasz C#, możesz uzyskać wszystkie dopasowania naraz, np. użyj Regex.Matches(), która zwraca MatchCollection (sprawdź indeks elementu, indeks% 2! = 0).
Jeśli chcesz znaleźć zdarzenie do zastąpienia go, użyj jednego z przeciążeń Regex.Replace(), które używają MatchEvaluator), np. Regex.Replace (String, String, MatchEvaluator, oto kod:.
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;
}
}
}
}
Może jestem zbyt wybredna, ale regex nie "znajdzie" niczego. Będzie tylko "dopasowywać" część twojego wejściowego łańcucha. To twój język programowania oferuje funkcje, które dopasowują ciąg do wyrażenia regularnego i zwracają różne informacje o dopasowaniu (np. Gdzie się pojawił). –
masz absolutną rację, jesteś zbyt wybredna;) –