正则表达式或单行代码操作字符串 [英] Regex or one liner code to manipulate string

查看:157
本文介绍了正则表达式或单行代码操作字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到以下几点:

String代码之前:

"don\'t" 
"a\\b"      

String代码之后:

"\"don\\\'t\""    
"\"a\\\\b\""

我已经写代码,这是否完美:

I have written code which does this perfectly:

string x = "";
x += "\"";
foreach (var item in s)
{
    if (item == '\'' || item == '\"' || item == '\\')
    {
        x += '\\';
    }
    x += item;
}
x += "\"";
return x;

但有一个更好的方式来做到这一点?单行代码?我不熟悉C#正则表达式,但我认为这可以用它来实现。
感谢您的帮助...

But is there a better way to do this? One liner code? I am not familiar with C# regex but I think this can be achieved with it. Thanks for any help...

推荐答案

有两个更好的把我的头顶部的方式:

There are two better ways off the top of my head:

    $ b $ :b
  1. 使用的StringBuilder 这就避免了多个中间字符串分配:

  1. Use StringBuilder. This avoids multiple intermediate string allocations:

var sb = new StringBuilder("\"");

foreach (var item in s)
{
    if (item == '\'' || item == '\"' || item == '\\')
        sb.Append('\\');

    sb.Append(item);
}

sb.Append('"');
return sb.ToString();


  • 正如你所说,使用正则表达式替换:

  • As you said, use a regex replacement:

    return "\"" + Regex.Replace(s, @"[\\'""]", "\\$&") + "\"";
    



    正则表达式是 [\\'] ,这意味着的匹配任何字符以下的: \ 的,和替换字符串 \ $&安培; 这意味着:用一个反斜杠后面替换此通过你刚才匹配

    The regex is [\\'"], which means match any of these chars: \ or ' or ", and the replacement string is \$& which means: replace this with a backslash followed by what you just matched.

    这两个字符串连接将被编译器重写一个 String.Concat 电话。

    The two string concatenations will be rewritten by the compiler to one String.Concat call.

    这篇关于正则表达式或单行代码操作字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆