代码之家  ›  专栏  ›  技术社区  ›  Archie

c regex将分隔符替换为另一个分隔符

  •  0
  • Archie  · 技术社区  · 16 年前

    我正在处理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_中使用regex?

    2 回复  |  直到 16 年前
        1
  •  4
  •   Svish    16 年前

    正则表达式:

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

    使用代码:

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

    没有用c测试,但是正则表达式和替换在regexbuddy中使用您的文本=)

    注:我不是一个非常出色的正则表达式作者,所以它可能写得更好。但它有效。处理这两种情况时,只需一行注释,从-开始,也可以使用/**来处理多行注释。/

    编辑:将您的评论读到另一个答案,因此删除了 ^ 锚定,这样它就可以处理不从新行开始的注释。

    编辑2:认为它可以简化一点。同时发现它在没有结束$anchor的情况下也可以正常工作。

    说明:

    // ((?:--|/\*)[^~]*)~(\*/)?
    // 
    // 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
  •  1
  •   gimel    16 年前

    实际上并不需要regex——您可以迭代行,定位以“-”开头的行,并将“~”替换为“~”。

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

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

    推荐文章