Home > Blockchain >  how to split base64 text into base64 strings c#
how to split base64 text into base64 strings c#

Time:11-05

I have a base64 text example:

UAAAAAAAAAA=AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=KAAAAAAAAAA=AAAAAAAA8D8AAAAAAAAAQAAAAAAAAAhAAAAAAAAAEEAAAAAAAAAAAA==

I need to split it into sides like this:

UAAAAAAAAAA=

AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=

KAAAAAAAAAA=

AAAAAAAA8D8AAAAAAAAAQAAAAAAAAAhAAAAAAAAAEEAAAAAAAAAAAA==

I tried:

string base64Text = "UAAAAAAAAAA=AA....."
Regex regex = new Regex(@"^[a-zA-Z0-9 /]*={0,2}$");
string[] base64Strings = regex.Split(base64Text);

CodePudding user response:

You could split on a position where there is a char A-Z or 0-9 to the left and not a = char or the end of the string to the right:

(?<=[A-Z0-9]=)(?!=|$)

Regex demo

string base64Text = @"UAAAAAAAAAA=AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=KAAAAAAAAAA=AAAAAAAA8D8AAAAAAAAAQAAAAAAAAAhAAAAAAAAAEEAAAAAAAAAAAA==";
Regex regex = new Regex(@"(?<=[A-Z\d]=)(?!=|$)");
string[] base64Strings = regex.Split(base64Text);
foreach (string s in base64Strings)
{   
    Console.WriteLine(s);
}

Output

UAAAAAAAAAA=
AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAA8D8AAAAAAADwPwAAAAAAAPA/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
KAAAAAAAAAA=
AAAAAAAA8D8AAAAAAAAAQAAAAAAAAAhAAAAAAAAAEEAAAAAAAAAAAA==
  • Related