如何替换字符串中花括号及其内容

8

我遇到了一个问题,需要用大括号括起来的字符串中的某些内容替换为外部值。

相关代码示例:

string value = "6";
string sentence = "What is 3 x {contents}";
# insert some sort of method sentence.replace(value,"{contents}");

在替换"{contents}"的值时,最好的方法是什么?考虑到花括号内的名称可能会更改,但无论名称如何,它都将包含在花括号内。

我稍微了解了一下正则表达式,但要么概念对我来说很难理解,要么我找不到相关的语法来完成我想做的事情。这是实现此目的的最佳方法吗?如果不是,有什么更好的方法可以实现这个目标?


请参见 https://dev59.com/62Qn5IYBdhLWcg3w1Z9f。 - Wiktor Stribiżew
5个回答

6
使用Regex.Replace函数:
string value = "6";
string sentence = "What is 3 x {contents}";
var result = Regex.Replace(sentence, "{.*?}", value); // What is 3 X 6

MSDN 是了解正则表达式的好起点。


谢谢,那么在这种情况下,.* 到底是做什么的?我知道它与添加内容有关,但每个项目分别完成了什么任务? - Zannith
5
现在是阅读有关正则表达式的入门指南的好时机,而不是针对每个小部分单独提问。 - Jon Skeet
正则表达式有误,请尝试用它替换“Example {text1} more text {text2}”。 - enkryptor
@Jon Skeet:是的,我之前也查找过相关信息,但我只找到了一些对于像我这样的初学者来说非常混乱的东西。您有没有好的学习资料推荐? - Zannith
@Zannith - 添加了一条链接来解释一些内容。 - Gilad Green

3

我通常最终会做出这样的事情:

        public static string FormatNamed(this string format, params object[] args)
        {
            var matches = Regex.Matches(format, "{.*?}");

            if (matches == null || matches.Count < 1)
            {
                return format;
            }

            if (matches.Count != args.Length)
            {
                throw new FormatException($"The given {nameof(format)} does not match the number of {nameof(args)}.");
            }

            for (int i = 0; i < matches.Count; i++)
            {
                format = format.Replace(
                    matches[i].Value,
                    args[i].ToString()
                );
            }

            return format;
        }


1
如果我正确理解你想做的事,并且假设你想替换文本中的每个"{contents}",我看到有两个解决方案:
  1. Using a simple string.Replace(string, string):

    public static string InsertContent(string sentence, string placeholder, string value)
    {
        return sentence.Replace("{" + placeholder + "}", value);
    }
    

    Note that the function returns a new string object.

  2. If you want to replace anything between brackets by a given value, or just have no control on what the string between brackets will be, you can also use a Regex :

    public static string InsertContent(string sentence, string value)
    {
        Regex rgx = new Regex(@"\{[^\}]*\}");
        return rgx.Replace(sentence, value);
    }
    

    Again, the function returns a new string object.


1

这个答案与@WizxX20的类似,但是这种V2方法具有更直观的行为和更高效的字符串替换逻辑,如果对大型文本文件运行此方法,则会变得更加明显。请自行判断:

string someStr = "I think I had {numCows} cows, wait actually it was {numCows} when I heard that serendipitous news at {time}.";
object[] args = new object[] { 3, 5, "13:45"};

//I think I had 3 cows, wait actually it was 3 when I heard that serendipitous news at 13:45.
Console.WriteLine(FormatNamed(someStr, args));

//"I think I had 3 cows, wait actually it was 5 when I heard that serendipitous news at 13:45."
Console.WriteLine(FormatNamedV2(someStr, args));



static string FormatNamedV2(string format, params object[] args)
{
    if(string.IsNullOrWhiteSpace(format))
        return format;

    var i = 0;  
    var sanitized = new Regex("{.*?}").Replace(format, m =>
    {
        //convert "NumTimes: {numTimes}, Date: {date}" to "NumTimes: {0}, Date: {1}" etc.
        var replacement = $"{{{i}}}";
        i++;
        return replacement;
    });

    if (i != args?.Length)
    {
        var formatPrettyPrint = format.Length > 16 ? $"{format.Substring(0, 16)}..." : format;
        throw new FormatException($"The given {nameof(format)} \"{formatPrettyPrint}\" does not match the number of {nameof(args)}: {args.Length}.");
    }

    return string.Format(sanitized, args);
}
    

0
你可以使用这段代码:
Regex.Replace(input, @"{[^{}]+}", "new string");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接