C#在字符串中插入值

C#在字符串中插入值,c#,regex,string,replace,C#,Regex,String,Replace,好的,基本上我有一个像这样的字符串 “这是随机文本[这也是随机的][另一个随机文本]嘿嘿嘿[随机条]” 我希望输出是 “这是随机文本[[这也是随机的][[另一个随机文本]]嘿,你好[[随机条]]” 所以基本上找到每一个[并在其上附加一个[和相同的] 最好的方法是什么?谢谢 所以基本上找到每一个[并在其上附加一个[和相同的] 听起来像: text = text.Replace("[", "[[") .Replace("]", "]]"); 对我来说…根本不需要正则表达式 当

好的,基本上我有一个像这样的字符串

“这是随机文本[这也是随机的][另一个随机文本]嘿嘿嘿[随机条]”

我希望输出是

“这是随机文本[[这也是随机的][[另一个随机文本]]嘿,你好[[随机条]]”

所以基本上找到每一个[并在其上附加一个[和相同的]

最好的方法是什么?谢谢

所以基本上找到每一个[并在其上附加一个[和相同的]

听起来像:

text = text.Replace("[", "[[")
           .Replace("]", "]]");
对我来说…根本不需要正则表达式

当然,这是假设你不需要担心已经加倍的括号

所以基本上找到每一个[并在其上附加一个[和相同的]

听起来像:

text = text.Replace("[", "[[")
           .Replace("]", "]]");
对我来说…根本不需要正则表达式


当然,这是假设您不需要担心括号已经翻了一倍。

或者您已经用regex标记了它:

var foo = "this is random text [this is random too] " +
    "[another random text] hey ho [random bar]";
var regex = new Regex(@"\[(.*?)\]");
string bar = regex.Replace(foo, @"[[$1]]");

或者考虑到你已经用正则表达式标记了它:

var foo = "this is random text [this is random too] " +
    "[another random text] hey ho [random bar]";
var regex = new Regex(@"\[(.*?)\]");
string bar = regex.Replace(foo, @"[[$1]]");

这将更有效,因为数组永远不需要调整大小。尽管差异如此之小,但使用Jon Skeet的方法可能会更好

public string InsertBrackets(string text)
{
    int bracketCount = 0;
    foreach (char letter in text)
        if (letter == '[' || letter == ']')
            bracketCount++;

    StringBuilder result = new StringBuilder(text.Length + bracketCount);

    for(int i = 0, j = 0; i < text.Length && j < result.Length; i++, j++)
    {
        result[j] = text[i];

        if (text[i] == '[')
            result[++j] = '[';
        else if (text[i] == ']')
            result[++j] = ']';
    }

    return result.ToString();
}
公共字符串插入括号(字符串文本)
{
int bracketCount=0;
foreach(文本中的字符)
如果(字母=='['|字母==']')
括号计数++;
StringBuilder结果=新的StringBuilder(text.Length+方括号计数);
对于(int i=0,j=0;i
这将更有效,因为数组永远不需要调整大小。尽管差异很小,但使用Jon Skeet的方法可能会更好

public string InsertBrackets(string text)
{
    int bracketCount = 0;
    foreach (char letter in text)
        if (letter == '[' || letter == ']')
            bracketCount++;

    StringBuilder result = new StringBuilder(text.Length + bracketCount);

    for(int i = 0, j = 0; i < text.Length && j < result.Length; i++, j++)
    {
        result[j] = text[i];

        if (text[i] == '[')
            result[++j] = '[';
        else if (text[i] == ']')
            result[++j] = ']';
    }

    return result.ToString();
}
公共字符串插入括号(字符串文本)
{
int bracketCount=0;
foreach(文本中的字符)
如果(字母=='['|字母==']')
括号计数++;
StringBuilder结果=新的StringBuilder(text.Length+方括号计数);
对于(int i=0,j=0;i
我觉得很愚蠢,这很好。谢谢。我会在8分钟内接受它。@user1224096:很高兴它成功了-比你想象的简单的问题总是比相反的好;)我觉得很愚蠢,这很好。谢谢。我会在8分钟内接受它。@user1224096:很高兴它成功了-比你想象的简单的问题总是更好相反;)@IanNorton我实际尝试的是使用.IndexOf然后.Insert。但效果不太好。我只是睡得很少,这就是结果。我甚至在问题中标记了replace,但没有意识到我可以使用它。@IanNorton我实际尝试的是使用.IndexOf然后.Insert。但效果不太好我只是睡得很少,这就是结果。我甚至在问题中加上了“替换”,但没有意识到我可以使用它。