C# Regex : 토큰을 런타임에 생성 된 문자열로 어떻게 교체 할 수 있습니까?
-
18-09-2019 - |
문제
다음 입력 및 정수 문자열이 주어지면 :
const string inputString = "${Principal}*${Rate}*${Years}";
const string tokenMatchRegexString = @"\${([^}]+)}";
각 토큰 (예 : $ {Principal}, $ {rate} 및 $ {reys}))를 'REPLACETOKE'함수의 반환 값으로 교체하려면 어떻게해야합니까?
private static string ReplaceToken(string tokenString)
{
switch (tokenString)
{
case "Principal":
return GetPrincipal();
case "Rate":
return GetRate();
case "Years":
return GetYears();
default:
throw new NotImplementedException(String.Format("A replacment for the token '{0}' has not been implemented.", tokenString));
}
}
private static string GetPrincipal()
{
throw new NotImplementedException();
}
private static string GetRate()
{
throw new NotImplementedException();
}
private static string GetYears()
{
throw new NotImplementedException();
}
해결책
REGEX에는 MatchEvaluator를 취하는 오버로드가 있습니다. 입력은 일치하고 문자열을 반환합니다. 이 경우 일치의 값은 전체 토큰이므로 값을 추출하는 심을 만들 수 있으며 (이미 Regex 내에서 이미 캡처하고 있음) 게시 한 메소드에 적응할 수 있습니다.
Regex.Replace(inputString,
tokenMatchRegexString,
match => TokenReplacement(match.Groups[1].Value));
다른 팁
미리 알고있는 것을 대체 할 토큰이 적다면 사용할 수 있습니다. string.Replace()
토큰을 하나씩 교체하려면. 이 간단한 기술은 작동 할 수 있지만 단점이 있습니다. 특히 확장 가능하지 않으며 중간 (Throwaway) 문자열을 초래할 수 있으며 코드가 혼란 스러울 수도 있습니다.
여러 가지 토큰이 있고 일관된 일치 규칙이 있다면 사용할 수 있습니다. Regex.Replace()
a MatchEvaluator
DELEGATE- 정규 표현식 일치를 받아들이고 일치를 대체하기 위해 문자열을 반환하는 기능. 사용의 이점 Replace()
과부하가 걸립니다 MatchEvaluator
그것은 다음 경기를 대체하는 데 사용되는 중간 줄의 생성을 피하는 데 도움이된다는 것입니다. 직접 굴리는 것이 아니라 내장 .NET 클래스를 재사용하는 것도 좋습니다.
마지막으로, 복잡한 일치/대체 요구 사항이 있으면 라이브러리를 사용할 수 있습니다. StringTemplate 보다 복잡한 템플릿 확장 및 일치 대체를 수행합니다.
다음은 사용의 예입니다 Regex.Replace()
전화:
const string inputString = "${Principal}*${Rate}*${Years}";
const string tokenMatchRegexString = @"\${([^}]+)}";
var rex = new Regex( tokenMatchRegexString );
MatchEvaluator matchEval = match => TokenReplacement( match.Groups[1].Value );
rex.Replace( inputString, matchEval );
바퀴를 재발 명하지 마십시오. 나는 사용한다 StringTemplate (C# 버전) 이런 일을 할 때.