Se si utilizza C#, è possibile ottenere tutte le corrispondenze contemporaneamente, ad es. usa Regex.Matches() che restituisce un MatchCollection (controlla l'indice dell'articolo, indice% 2! = 0).
Se si vuole trovare il verificarsi di sostituirlo, utilizzare uno dei sovraccarichi di Regex.Replace() che utilizzano un MatchEvaluator), ad esempio, Regex.Replace (String, String, MatchEvaluator, ecco il codice:.
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;
}
}
}
}
fonte
2009-02-26 10:06:06
Forse sono troppo schizzinoso ma un regex non "trova" nulla. Sarà solo "abbinare" una parte della stringa di input. È il tuo linguaggio di programmazione che ti offre funzioni per abbinare una stringa a una regex e restituire varie informazioni sulla partita (ad esempio dove si è verificato). –
hai assolutamente ragione, siete troppo esigente;) –