c# - 正则表达式 - 在特定情况下替换 C# 字符串中的字符

标签 c# regex string replace

只有当输入字符串中没有数字时,我才想将所有括号替换为另一个括号。我编写了这个工作代码示例:

    string pattern = @"(\{[^0-9]*?\})";
                MatchCollection matches = Regex.Matches(inputString, pattern);
                if(matches != null)
                {
                    foreach (var match in matches)
                    {
                        string outdateMatch = match.ToString();
                        string updateMatch = outdateMatch.Replace('{', '[').Replace('}', ']');
                        inputString = inputString.Replace(outdateMatch, updateMatch);
                    }
                }

所以对于:

string inputString = "{0}/{something}/{1}/{other}/something"

结果将是:

inputString = "{0}/[something]/{1}/[other]/something"

是否可以使用 Regex.Replace() 方法在一行中完成此操作?

最佳答案

您可以使用

var output = Regex.Replace(input, @"\{([^0-9{}]*)}", "[$1]");

请参阅regex demo .

详细信息

  • \{ - 一个 { 字符
  • ([^0-9{}]*) - 捕获组 1:除数字、{} 之外的 0 个或多个字符>
  • } - 一个 } 字符。

替换为 [$1],即用方括号括起来的第 1 组的内容。

关于c# - 正则表达式 - 在特定情况下替换 C# 字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53009101/

相关文章:

c# - 提取链接正则表达式 c#

java - 正则表达式以字符串开头,匹配所有类型的符号、字符、数字

java - 交换没有临时变量的字符串值

C# 正则表达式 : match a string starting with x and ending with y, 不包括结尾部分 & 匹配模式的最后一次出现

c# - 在 C# 中引发异常的最佳方法是什么?

c# - CheckBox 不将选中的值发送到数据库 C# Asp

c# - Visual Studio 运行 .NET 应用程序中的调试日志文件位置

c# - 为什么我的 Kendo AutoComplete 小部件没有绑定(bind)到 JSON 对象?

php - 用于检查 URL 是否为短 URL 的 Regex/php 代码

r - str_replace 不会替换所有出现的内容,但是 gsub 会替换吗?