使用正则表达式将插值字符串转换为string.Format

时间:2016-09-02 07:13:43

标签: c# regex

我和我的同事有不同版本的VisualStudio。他使用插值字符串,我无法构建解决方案,必须将它们全部转换为string.Format。

现在我认为这对正则表达式来说可能是一个很好的练习。

那么如何转换它:

$"alpha: {alphaID}, betaValue: {beta.Value}"

对此:

string.Format("alpha: {0}, betaValue: {1}", alphaID, beta.Value)

现在变量的数量可以变化(比方说1 - 20,但应该是通用的)

我想出了这个正则表达式,以匹配第一个变量

\$.*?{(\w+)}

但我无法弄清楚如何在美元符号后重复该部分,所以我可以重复结果。

4 个答案:

答案 0 :(得分:2)

Regex.Replace有一个带有函数的重载,称为MatchEvaluator。你可以像这样使用它;

 var paramNumber = 0;     
 var idNames = new List<string>();
 myCSharpString = Regex.Replace(myCSharpString, match => {
    // remember the id inside brackets;
    idNames.Add(match.ToString());

    // return "0", then "1", etc.
    return (paramNumber++).ToString();
 });

在此过程结束时,您的"this is {foo} not {bar}"字符串将替换为"this is {0} not {1}",您将拥有一个包含{ "foo" , "bar" }的列表,您可以使用该列表组合参数列表。

答案 1 :(得分:2)

您可以在旧版Visual Studio using the C# 6 nuget package

中使用C#6功能

基本上,只需使用

Install-Package Microsoft.Net.Compilers

在所有项目上。

答案 2 :(得分:0)

我没有c#的经验,但这可能会对您有所帮助:

\{(.+)}\gU

<强>解释

{ matches the character { literally

. matches any character (except newline)

Quantifier: + Between one and unlimited times, as few times as possible, expanding as needed [lazy]

} matches the character } literally

g modifier: global. All matches (don't return on first match)

U modifier: Ungreedy

答案 3 :(得分:0)

以下几个选项不涉及正则表达式:

  1. 您可以使用ReSharper。它内置了这样的转换。
  2. 如果您不想为ReSharper付款,请使用Roslyn编写自定义代码修复程序。从string.format到插值字符串的Here is an example,你只需要反转它。

  3. 手动执行

  4. 如果可以的话,请你的同事为你做这件事。
  5. 更新VS