正则表达式替换:使用自定义函数转换模式 [英] Regex replace: Transform pattern with a custom function
问题描述
假设我有一些这样的文本:
Let's say I have some text such as this:
[MyAppTerms.TermName1].[MyAppTerms.TermName2].1- [MyAppTerms.TermNameX] 2- ...
[MyAppTerms.TermName1]. [MyAppTerms.TermName2]. 1- [MyAppTerms.TermNameX] 2- ...
我想用 ReadTerm( "MyAppTerms.Whatever" )
的结果替换每次出现的 [MyAppTerms.Whatever]
,其中 ReadTerm
是一个静态函数,它接收术语名称并返回当前语言的术语文本.
I want to replace every occurrence of [MyAppTerms.Whatever]
with the result of ReadTerm( "MyAppTerms.Whatever" )
, where ReadTerm
is a static function which receives a term name and returns the term text for the current language.
使用Regex.Replace
是否可行?(欢迎替代).我正在研究替换组,但不确定是否可以将函数与它们一起使用.
Is this feasible using Regex.Replace
? (alternatives are welcome). I'm looking into substitution groups but I'm not sure if I can use functions with them.
推荐答案
使用 Regex.Replace(String, MatchEvaluator)
重载.
Use the Regex.Replace(String, MatchEvaluator)
overload.
static void Main()
{
string input = "[MyAppTerms.TermName1]. [MyAppTerms.TermName2]. 1- [MyAppTerms.TermNameX] 2";
Regex regex = new Regex(@"\[MyAppTerms\.([^\]]+)\]");
string output = regex.Replace(input, new MatchEvaluator(RegexReadTerm));
Console.WriteLine(output);
}
static string RegexReadTerm(Match m)
{
// The term name is captured in the first group
return ReadTerm(m.Groups[1].Value);
}
模式 \[MyAppTerms\.([^\]]+)\]
匹配您的 [MyAppTerms.XXX]
标签并捕获 XXX
在捕获组中.然后在您的 MatchEvaluator
委托中检索该组并将其传递给您实际的 ReadTerm
方法.
The pattern \[MyAppTerms\.([^\]]+)\]
matches your [MyAppTerms.XXX]
tags and captures the XXX
in a capture group. This group is then retrieved in your MatchEvaluator
delegate and passed to your actual ReadTerm
method.
使用 lambda 表达式会更好(自 C# 3.0 起):
It's even better with lambda expressions (since C# 3.0):
static void Main()
{
string input = "[MyAppTerms.TermName1]. [MyAppTerms.TermName2]. 1- [MyAppTerms.TermNameX] 2";
Regex regex = new Regex(@"\[MyAppTerms\.([^\]]+)\]");
string output = regex.Replace(input, m => ReadTerm(m.Groups[1].Value));
Console.WriteLine(output);
}
在这里,您直接在使用它的代码内部定义评估器(将逻辑连接的代码段保持在一起),而编译器负责构建该 MatchEvaluator
委托.
Here, you define the evaluator straight inside the code which uses it (keeping logically connected pieces of code together) while the compiler takes care of constructing that MatchEvaluator
delegate.
这篇关于正则表达式替换:使用自定义函数转换模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!