【问题标题】:ignore value in curly braces忽略花括号中的值
【发布时间】:2018-07-19 20:45:38
【问题描述】:
public static string ToKebabCase(this string value)
{
    if (string.IsNullOrEmpty(value))
        return value;

    return Regex.Replace(
                value,
                "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])",
                "-$1",
                RegexOptions.Compiled)
            .Trim()
            .ToLower();
}

此方法制作字符串

"{branchId}/GetUser/{userId}" -> "{branch-id}/-get-user/{user-id}"

我需要:

 "{branchId}/get-user/{userId}"

如何忽略花括号中的值?

【问题讨论】:

    标签: c# .net regex regex-lookarounds


    【解决方案1】:

    这只是“并非所有事情都必须用正则表达式解决”的一个例子

    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();
    }
    

    RegEx 解决方案可能是

    public static string ToKebabCase(string value)
    {
       if (string.IsNullOrEmpty(value))
          return value;
    
       return Regex.Replace(value, @"(?<!/)([A-Z])(?![^\{\}]*\})", "-$1").Trim()
    }
    

    内容如下

    前面没有/

    (?<!/)
    

    大写字母

    ([A-Z])
    

    不在括号内

    (?![^\{\}]*\})
    

    【讨论】:

    • 所有变体都返回 {branchid}/get-user/{userid},但我需要 {branchId}/get-user/{userId}。有可能吗?
    • @AlexanderIvanov 你需要第一个,我已经更新了
    【解决方案2】:

    也许您可以在第 1 组中捕获 {branchId},在第 2 组中捕获 Get,在第 3 组中捕获 User,在第 4 组中捕获 {userId},作为示例字符串:

    ({[^}]+})(\/[A-Z][a-z]+)([A-Z][a-z]+\/)({[^}]+})

    在替换中您将使用$1$2-$3$4

    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;
    }
    

    Demo output C#

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 2019-01-26
      • 2011-05-31
      • 2016-01-10
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多