1

I want to only encode a substring in my string, here test from String str = \"test"\

Is there a better way to do this than what I did below? Perhaps through an regEx?

var fullStr = "\"\\test\"\\";
char[] charsToTrim = { '\"', '\\'};
string result = fullStr.Trim(charsToTrim);
string StrEncoded =  Convert.ToBase64String(Encoding.UTF8.GetBytes(result));

string retStr = "\"\\" + StrEncoded + "\"\\";
Lubbi
  • 91
  • 1
  • 6
  • why don't use a [verbatim string](https://stackoverflow.com/q/3311988/995714) to make it more readable: `@"""\test""\"`, `@"""\"`, `@"""\"`? – phuclv Oct 10 '20 at 06:54

2 Answers2

0

You might be looking for this regex

(?<="\\).*?(?="\\)

(?<="\\) - > Positive lookbehind (check if there are these characters behind you) (?="\\) - > Positive lookahead (check if there are these characters ahead of you)

.* -> Select everything in between

The new code:

        var fullStr = "\"\\test\"\\";
        char[] charsToTrim = { '\"', '\\'};
        string result = fullStr.Trim(charsToTrim);
        Console.WriteLine(result);
        string pattern = "(?<=\"\\\\).*?(?=\"\\\\)";
        var m = Regex.Match(fullStr, pattern, RegexOptions.IgnoreCase);
        Console.WriteLine(m.Value);

And dotnet fiddle example

My guess is you are looking for the following:

string pattern = "(?<=\"\\\\).*?(?=\\\\\")";
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • You may want to use `.*?` instead of `.*` as the latter will match everything from the first quote to the last in the input (greedy) which is probably wrong if the input contains multiple "..." parts. – Klaus Gütter Oct 11 '20 at 04:52
  • Good thinking Klaus, I'll update the answer with your suggestion. – Athanasios Kataras Oct 11 '20 at 07:47
0

You can use Regex.Match() with a MatchEvaluator.

...
string retStr = Regex.Replace(fullStr, "test", delegate (Match match)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(match.Value));
});
...
sticky bit
  • 36,626
  • 12
  • 31
  • 42