C# 忽略大括号中的值
我需要:C# 忽略大括号中的值,c#,.net,regex,regex-lookarounds,C#,.net,Regex,Regex Lookarounds,我需要: "{branchId}/GetUser/{userId}" -> "{branch-id}/-get-user/{user-id}" 如何忽略大括号中的值?这只是“并非所有问题都必须用正则表达式解决”的一个例子 RegEx解决方案可能是 public static string ToKebabCase(this string value) { if (string.IsNullOrEmpty(value)) return value; var lis
"{branchId}/GetUser/{userId}" -> "{branch-id}/-get-user/{user-id}"
如何忽略大括号中的值?这只是“并非所有问题都必须用正则表达式解决”的一个例子
RegEx
解决方案可能是
public static string ToKebabCase(this string value)
{
if (string.IsNullOrEmpty(value))
return value;
var list = value.Split('/');
list[1] = Regex.Replace(list[1], "([A-Z])", "-$1").ToLower();
return string.Join("/", list).Trim();
}
大写字母
(?<!/)
不在括号内
([A-Z])
也许您可以在组1中捕获
{branchId}
,在组2中捕获Get
,在组3中捕获User
,在组4中捕获{userId}
作为示例字符串,并使用:
在替换中,您将使用$1$2-$3$4
(?![^\{\}]*\})
所有变量都返回{branchid}/get user/{userid},但我需要{branchid}/get user/{userid}。有可能吗?@AlexanderIvanov你需要第一个,我已经更新了
(?<!/)
([A-Z])
(?![^\{\}]*\})
public static string ToKebabCase(this string value)
{
if (string.IsNullOrEmpty(value))
return value;
Regex r1 = new Regex(@"({[^}]+})(\/[A-Z][a-z]+)([A-Z][a-z]+\/)({[^}]+})");
Match match = r1.Match(value);
if (match.Success) {
value = String.Format("{0}{1}-{2}{3}",
match.Groups[1].Value,
match.Groups[2].Value.ToLower(),
match.Groups[3].Value.ToLower(),
match.Groups[4].Value
);
}
return value;
}