什么是这个ironpython代码的C#版本

时间:2011-09-06 16:12:22

标签: c# regex ironpython

我需要在C#中编写这个IronPython代码(我找不到类似的C#库来匹配IronPython的re模块):

for v in variables:
  replace = re.compile(v, re.IGNORECASE)...
  re.sub(v, str(self.SQLVariables[v.upper().replace("&","")]),script_content)...

换句话说,什么是等效于以下表达式的C#:

  • re.compile(...)...
  • 应用re.sub(...)...

1 个答案:

答案 0 :(得分:7)

您的问题归结为,如何在C#中使用正则表达式?

答案是Regex课程。要执行替换,您需要Regex.Replace()。没有必要显式编译正则表达式,因为这是在创建Regex实例时完成的。


以下example from MSDN说明了如何使用该课程:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is   text with   far  too   much   " + 
                     "whitespace.";
      string pattern = "\\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   whitespace.
//       Replacement String: This is text with far too much whitespace.