Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to split string into equal length chunks

Tags:

c#

regex

I have a string which would be delivered to my application in the format below:

ece4241692a1c7434da51fc1399ea2fa155d4fc983084ea59d1455afc79fafed

What I need to do is format it for my database so it reads as follows:

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

I assume the easiest way to do this would be using regular expressions, but I have never used them before, and this is the first time I have ever needed to, and to be honest, I simply don't have the time to read up on them at the moment, so if anyone could help me with this I would be eternally grateful.

like image 476
Mick Walker Avatar asked Jan 20 '10 12:01

Mick Walker


People also ask

How do you split a string into chunks in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

How do you split a string by the occurrences of a regex pattern?

split() method split the string by the occurrences of the regex pattern, returning a list containing the resulting substrings.


2 Answers

What about:

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

Or

string another = "<" + String.Join(" ", Regex.Split(input, "(.{8})")) + ">";
like image 138
Rubens Farias Avatar answered Nov 05 '22 09:11

Rubens Farias


You might just be better served having a small static string parsing method to handle it. A regular expression might get it done, but unless you're doing a bunch in a batch you won't save enough in system resources for it to be worth the maintenance of a RegEx (if you're not already familiar with them I mean). Something like:

    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() + ">";
    }
like image 27
Joel Etherton Avatar answered Nov 05 '22 09:11

Joel Etherton