代码之家  ›  专栏  ›  技术社区  ›  Mick Walker

将字符串拆分为等长块的正则表达式

  •  5
  • Mick Walker  · 技术社区  · 15 年前

    我有一个字符串,将按以下格式发送到我的应用程序:

    ece4241692a1c7434da51fc1399ea2fa155d4fc983084ea59d1455afc79fafed
    

    我需要做的是为我的数据库格式化它,使其如下所示:

    <ece42416 92a1c743 4da51fc1 399ea2fa 155d4fc9 83084ea5 9d1455af c79fafed>
    

    我认为最简单的方法是使用正则表达式,但我以前从未使用过,这是我第一次需要使用正则表达式,老实说,我现在根本没有时间阅读它们,所以如果有人能帮助我,我将永远感激。

    3 回复  |  直到 13 年前
        1
  •  2
  •   Rubens Farias    15 年前

    如何:

    string input ="ece4241692a1c7434da51fc1399ea2fa155d4fc983084ea59d1455afc79fafed";
    string target = "<" + Regex.Replace(input, "(.{8})", "$1 ").Trim() + ">";
    

    string another = "<" + String.Join(" ", Regex.Split(input, "(.{8})")) + ">";
    
        2
  •  2
  •   Joel Etherton    15 年前

    您最好有一个小的静态字符串解析方法来处理它。一个正则表达式可能会完成它,但是除非你在一个批处理中做了大量的工作,否则你将无法在系统资源中节省足够的资源来维护一个regex(如果你还不熟悉它们,我的意思是)。类似:

        private string parseIt(string str) 
        {
            if(str.Length % 8 != 0) throw new Exception("Bad string length");
            StringBuilder retVal = new StringBuilder(str)
            for (int i = str.Length - 1; i >=0; i=i-8)
            {
                retVal.Insert(i, " ");    
            }
            return "<" + retVal.ToString() + ">";
        }
    
        3
  •  2
  •   Josh Lee ZZ Coder    15 年前

    尝试

    Regex.Replace(YOURTEXT, "(.{8})", "$1 ");