简体   繁体   English

C#将值插入字符串

[英]C# insert values to string

Ok so basically I have a string that looks like this 好吧,基本上我有一个看起来像这样的字符串

"this is random text [this is random too] [another random text] hey ho [random bar]" “这是随机文本[也是随机文本] [另一个随机文本]嘿[随机酒吧]”

I want the output to be 我希望输出是

"this is random text [[this is random too]] [[another random text]] hey ho [[random bar]]" “这是随机文本[[也是随机文本] [[另一个随机文本]]嘿[[随机条]]”

So basically find every [ and append an [ to it and same for the ] 因此,基本上找到每个[并在其后附加一个[和]相同

What would be the best way to do this? 最好的方法是什么? Thanks. 谢谢。

So basically find every [ and append an [ to it and same for the ] 因此,基本上找到每个[并在其后附加一个[和]相同

Sounds like: 听起来好像:

text = text.Replace("[", "[[")
           .Replace("]", "]]");

to me... no need for a regular expression at all. 对我来说...根本不需要正则表达式。

That is assuming you don't need to worry about brackets which are already doubled, of course. 当然,这是假设您不必担心已经加倍的括号。

This will be more efficient because the array will never have to be resized. 这将更加高效,因为永远不必调整数组的大小。 Although the difference is so small you're probably better off using Jon Skeet's method. 尽管差异很小,但您最好使用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();
}

Or given you've tagged this with 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]]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM