C#控制台 - 动态正则表达式替换

时间:2014-06-02 03:25:00

标签: c# regex

我有一点问题,但还没有找到解决方法。 好吧,我正在做一个转换器,我需要使用一个正常的表达式,它将起作用,直到它之后找不到任何东西。 我的字符串是:

with System, System.IO, System.Text // and it can go more and more and more

我要用{后面跟着名称替换with之后的所有内容,然后,代码将转换为:

using System;
using System.IO;
using System.Text;

我可以用静态号码来做,但我不想限制它们。我目前的REGEX是

"with (.*), (.*), (.*)"

替换为

"using $1;\n using $2;\n using $3;\n"

有没有办法让它动态化? 提前谢谢。

2 个答案:

答案 0 :(得分:2)

此正则表达式将所有字符串捕获到第1组:

(?:with\s|\G)([^,]*)(?:,\s*|$)

将它们全部匹配,然后迭代Group 1捕获以构建Using字符串。当然,这只是其中几种方法之一。

请参阅demo(查看右下方窗格中的第1组捕获)

解释正则表达式

(?:                      # group, but do not capture:
  with                   #   'with'
  \s                     #   whitespace (\n, \r, \t, \f, and " ")
 |                       #  OR
  \G                     #   where the last m//g left off
)                        # end of grouping
(                        # group and capture to \1:
  [^,]*                  #   any character except: ',' (0 or more
                         #   times (matching the most amount
                         #   possible))
)                        # end of \1
(?:                      # group, but do not capture:
  ,                      #   ','
  \s*                    #   whitespace (\n, \r, \t, \f, and " ") (0
                         #   or more times (matching the most amount
                         #   possible))
 |                       #  OR
  $                      #   before an optional \n, and the end of
                         #   the string
)                        # end of grouping

此示例代码输出您想要的内容(请参阅online demo)

底部的结果
using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
class Program
{
static void Main() {
string s1 = @"with System, System.IO, System.Text";
var myRegex = new Regex(@"(?:with\s|\G)([^,]*)(?:,\s*|$)");
var group1Caps = new StringCollection();

Match matchResult = myRegex.Match(s1);
// put Group 1 captures in a list
while (matchResult.Success) {
if (matchResult.Groups[1].Value != "") {
group1Caps.Add(matchResult.Groups[1].Value);
}
matchResult = matchResult.NextMatch();
}

string usingStr  = "";
foreach (string match in group1Caps) usingStr = usingStr + "Using " + match + ";\n";
Console.WriteLine(usingStr);

Console.WriteLine("\nPress Any Key to Exit.");
Console.ReadKey();

} // END Main
} // END Program

答案 1 :(得分:0)

使用Capture属性为单个捕获组获取多个值:

string inp = "with System, System.IO, System.Text";
string repl = Regex.Replace(
        inp, @"^with (?:(?<namespace>.+?)\s*(?:,\s*|$))*$",
            a => String.Join(
                  Environment.NewLine,
                  a.Groups["namespace"]
                    .Captures
                    .OfType<Capture>()
                    .Select(b => String.Format("using {0};", b))
                   )
               );
Console.WriteLine(repl);

打印repl的内容:

using System;
using System.IO;
using System.Text;