【问题标题】:C# regex to replace a delimiter by another oneC# 正则表达式用另一个分隔符替换分隔符
【发布时间】:2009-03-17 08:01:15
【问题描述】:

我正在处理要替换“;”的 pl/sql 代码用'~'注释。

例如

如果我有一个代码:

--comment 1 with;
select id from t_id;
--comment 2 with ;
select name from t_id;
/*comment 3 
with ;*/

然后我希望我的结果文本为:

--comment 1 with~
select id from t_id;
--comment 2 with ~
select name from t_id;
/*comment 3 
with ~*/

可以在 C# 中使用正则表达式吗?

【问题讨论】:

    标签: c# regex parsing plsql csv


    【解决方案1】:

    正则表达式:

    ((?:--|/\*)[^~]*)~(\*/)?
    

    使用它的 C# 代码:

    string code = "all that text of yours";
    Regex regex = new Regex(@"((?:--|/\*)[^~]*)~(\*/)?", RegexOptions.Multiline);
    result = regex.Replace(code, "$1;$2");
    

    未使用 C# 测试,但正则表达式和替换在 RegexBuddy 中与您的文本一起工作 =)

    注意:我不是一个非常出色的正则表达式编写者,所以它可能会写得更好。但它有效。并使用以 -- 开头的 one-liner-cmets 处理您的情况,以及以 /* */

    开头的多行情况

    编辑:阅读您对另一个答案的评论,因此删除了 ^ 锚点,以便它处理 cmets 也不会从新行开始。

    编辑 2:认为它可以简化一点。还发现它在没有结尾 $ 锚的情况下也能正常工作。

    说明:

    // ((?:--|/\*)[^~]*)~(\*/)?
    // 
    // Options: ^ and $ match at line breaks
    // 
    // Match the regular expression below and capture its match into backreference number 1 «((?:--|/\*)[^~]*)»
    //    Match the regular expression below «(?:--|/\*)»
    //       Match either the regular expression below (attempting the next alternative only if this one fails) «--»
    //          Match the characters “--” literally «--»
    //       Or match regular expression number 2 below (the entire group fails if this one fails to match) «/\*»
    //          Match the character “/” literally «/»
    //          Match the character “*” literally «\*»
    //    Match any character that is NOT a “~” «[^~]*»
    //       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
    // Match the character “~” literally «~»
    // Match the regular expression below and capture its match into backreference number 2 «(\*/)?»
    //    Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
    //    Match the character “*” literally «\*»
    //    Match the character “/” literally «/»
    

    【讨论】:

      【解决方案2】:

      真正需要正则表达式 - 您可以迭代行,找到以“--”开头的行并替换“;”上面有“~”。

      String.StartsWith("--") - 确定 String 实例的开头是否与指定的字符串匹配。

      String.Replace(";", "~") - 返回一个新字符串,其中在该实例中出现的所有指定 Unicode 字符或字符串都替换为另一个指定的 Unicode 字符或字符串。

      【讨论】:

      • 好吧,问题是我必须在换行符上拆分它。我不想,因为我有一个太大的代码。此外,对于像 select *from g;--select 语句这样的代码,我可能无法替换 ;在评论中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多