이렇게해야합니다.
int count = 0;
string text = Regex.Replace(text,
@"(((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", //Example expression. This one captures URLs.
match =>
{
string replacementValue = String.Format("<a href='{0}'>{0}</a>", match.Value);
count++;
return replacementValue;
});
나는 내가 지금 당장 할 수 없습니다 내 dev에 컴퓨터에 아니지만, 나중에 실험 람다 표현식이 작업을 수행하는 방법이 아닌 방법을 선언이 있는지 확인하기 위하여려고하고있다 IncrementCount() int를 증가시킵니다.
EDIT은 다른 방법을 선언하는 대신 람다 식을 사용하도록 수정되었습니다.
EDIT2 패턴을 미리 알지 못하더라도 일치 객체에 포함 된 모든 그룹 (참조하는 $ 그룹)을 GroupCollection에 포함시킬 수 있습니다. 그래서 같이 : 당신이 생산 가지고
int cnt = 0;
string result = Regex.Replace("aaa", "a", m => {
cnt++;
return "b";
});
두 번째 사건은 까다 롭습니다 :
int count = 0;
string text = Regex.Replace(text,
@"(((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)", //Example expression. This one captures URLs.
match =>
{
string replacementValue = String.Format("<a href='{0}'>{0}</a>", match.Value);
count++;
foreach (Group g in match.Groups)
{
g.Value; //Do stuff with g.Value
}
return replacementValue;
});
이것은 정규식 검색으로 호출하여 패턴을 명령 줄 인수로 대체 할 수있는 간단한 명령 줄 유틸리티입니다. 그래서 이상적으로 패턴에 대한 지식을 미리 알지 못하는 일반 솔루션이 필요합니다. 정말로 이것이 관심사이지만 - 닷넷에서 이것을하는 가장 좋은 방법은 무엇입니까? $ replacement의 수동 구문 분석과 함께 MatchEvaluator 접근 방식이 앞으로 나아갈 것으로 보이지만 약간 지저분합니다. ( –
Simon, 내 편집 참조 – Chev