C# 替换尖括号之间的字符
故事: 我有一个列表框,显示当前应用程序的所有方法。我需要将方法参数的数据类型着色为蓝色 解决方案:首先,我提取括号之间的内容。第二,我想用逗号把它们分开 问题: 如果参数包含像C# 替换尖括号之间的字符,c#,regex,string,C#,Regex,String,故事: 我有一个列表框,显示当前应用程序的所有方法。我需要将方法参数的数据类型着色为蓝色 解决方案:首先,我提取括号之间的内容。第二,我想用逗号把它们分开 问题: 如果参数包含像IDictionary这样多次出现的内容,那么上述解决方案将面临问题!!因此,我决定首先抓取尖括号之间的所有内容,然后用“#comma#”替换它们的逗号,在使用上述解决方案执行任务后,只需将“#comma#”替换为“,”。但是,根据找到的解决方案,无法将任何值设置为match.value。这是我的密码: if (meth
IDictionary
这样多次出现的内容,那么上述解决方案将面临问题!!因此,我决定首先抓取尖括号之间的所有内容,然后用“#comma#”
替换它们的逗号,在使用上述解决方案执行任务后,只需将“#comma#”
替换为“,”。但是,根据找到的解决方案,无法将任何值设置为match.value
。这是我的密码:
if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
{
var regex = new Regex("(?<=<).*?(?=>)");
foreach (Match match in regex.Matches(methodArgumentType))
{
match.Value = match.Value.Replace(",", "#COMMA#");
}
}
if(methodArgumentType.Contains(“”)
{
var regex=new regex((?您需要在regex.replace
中替换匹配计算器中的匹配值):
var methodArgumentType=“IDictionary”;
if(methodArgumentType.Contains(“”)
{
methodArgumentType=Regex.Replace(methodArgumentType,@“”,
m=>string.Format(“,m.Groups[1].Value.Replace(“,”,“#逗号#”);
}
Console.WriteLine(methodArgumentType);
//=>IDictionary
,m.Groups[1]。Value
将保存string,string
,替换将在输入字符串本身上完成,而不是在Regex.Match
对象上完成。您需要替换Regex.replace
中匹配计算器内的匹配值:
var methodArgumentType=“IDictionary”;
if(methodArgumentType.Contains(“”)
{
methodArgumentType=Regex.Replace(methodArgumentType,@“”,
m=>string.Format(“,m.Groups[1].Value.Replace(“,”,“#逗号#”);
}
Console.WriteLine(methodArgumentType);
//=>IDictionary
,m.Groups[1].Value
将保留string,string
并且替换将在输入字符串本身上进行,而不是在Regex.Match
对象上进行。@Tushar:我认为Regex模式没有问题。实际上,Match.Value
是只读的,不能替换。也许我需要做些其他的事情。你可以用来做e> methodArgumentType=Regex.Replace(methodArgumentType,@“”,m=>string.Format(“,m.Groups[1].Value.Replace(“,”,“#COMMA#)”)
。然后,IDictionary
将变成IDictionary
。这是您想要实现的吗?固定模式为@"
。为什么不直接使用Roslyn获取代码的语法树?@Stribizev:非常感谢您的帮助。它帮了很多忙。对不起,我对Regex不是很有信心concept@Tushar:我不认为正则表达式模式是否有问题。实际上,match.Value
是只读的,不能替换。也许我需要做些其他事情。你可以st可以使用methodArgumentType=Regex.Replace(methodArgumentType,@“”,m=>string.Format(“,m.Groups[1].Value.Replace(“,”,“#COMMA#)”)
)来完成它。然后,IDictionary
将变成IDictionary
。这是您想要实现的吗?固定模式为@“
。为什么不直接使用Roslyn获取代码的语法树?@Stribizev:非常感谢您的帮助。它帮助了很多。对不起,我对Regex概念没有太大信心非常感谢您的帮助回答非常感谢您的帮助回答
var methodArgumentType = "IDictionary<string, string>";
if (methodArgumentType.Contains("<") && methodArgumentType.Contains(">"))
{
methodArgumentType = Regex.Replace(methodArgumentType, @"<([^<>]+)>",
m => string.Format("<{0}>", m.Groups[1].Value.Replace(",", "#COMMA#")));
}
Console.WriteLine(methodArgumentType);
// => IDictionary<string#COMMA# string>