Regular expression to split a string into equal lengths

I have a string that will be delivered to my application in the following format:

ece4241692a1c7434da51fc1399ea2fa155d4fc983084ea59d1455afc79fafed

What I need to do is format it for my database so that it reads the following:

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

I guess the easiest way to do this is to use regular expressions, but I have never used them before, and this is the first time I've ever needed, and to be honest, I just don't have time to read them at this moment, so if anyone can help me, I will be forever grateful.

+5
source share
3 answers

What about:

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

or

string another = "<" + String.Join(" ", Regex.Split(input, "(.{8})")) + ">";
+2
source

Try

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

You might be better off if you have a little string parsing method to handle it. A regular expression can do this, but if you are not doing a bunch in a package, you will not save enough on system resources to make it worth maintaining RegEx (if you are not already familiar with them, I mean). Sort of:

    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() + ">";
    }
+2
source

All Articles