I have a qwestion. How can i find and replace a part of text using regex. If someone help me, I will be very glad. Here is the code:
Regex yourRegex = new Regex("(?<=\\[base64])(.*?)(?=\\[\\/base64])");
string result = yourRegex.Replace(Uri.UnescapeDataString(Body)),Helpers.Base64Encode(Convert.ToString(yourRegex)));
letterData.body = result;
All what I need, is to find in body, text that will be between [base64] HERE [/base64]. And replace this text with base 64 encoded text without "[base64][/base64]"
Example: [base64] Hi my name [/base64] is Andrew, how are you
Result: SGkgbXkgbmFtZQ== is Andrew, how are you
CodePudding user response:
You can turn the lookarounds into matches followed by optional whitspace chars as you don't want to keep the [base64]
and [/base64]
after the replacement.
Then making use of Replace with a callback function, you can take the capture group 1 value to be converted to base64.
var Body = @"[base64] Hi my name [/base64] is Andrew, how are you";
Regex yourRegex = new Regex(@"(?s)\[base64]\s*(.*?)\s*\[/base64]");
string result = yourRegex.Replace(Body, m =>
System.Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(m.Groups[1].Value)
)
);
Console.WriteLine(result);
Output
SGkgbXkgbmFtZQ== is Andrew, how are you