【问题标题】:MVC nice urls and special chars in regex正则表达式中的 MVC 漂亮 url 和特殊字符
【发布时间】:2013-06-06 18:50:37
【问题描述】:

如何编辑此正则表达式 Regex.Replace(encodedUrl, @"[^a-z0-9]", "-"); 以不删除 ę,ą,ó,ł 等特殊字符?

这是我的方法。我用它来生成漂亮的 URL,在 URL 中没有这些字符 .,#$%@:;

    public static string ToSeoUrl(this string url)
    {
        // make the url lowercase
        string encodedUrl = (url ?? "").ToLower();

        // replace & with and
        encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");

        // remove characters
        encodedUrl = encodedUrl.Replace("'", "");

        // remove invalid characters
        encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");

        // remove duplicates
        encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");

        // trim leading & trailing characters
        encodedUrl = encodedUrl.Trim('-');

        return encodedUrl;
    }

问候

【问题讨论】:

  • 您专门删除了不是 a-z0-9 的任何内容 - 如果您有要保留的特定字符,请将它们添加到该列表中。如果您没有有限列表,则需要重新考虑如何进行替换。

标签: c# asp.net-mvc regex


【解决方案1】:

您可以将特殊字符添加到字符类中:

@"[^a-z0-9ęąół]"

正则表达式基本上匹配任何不是 a-z、0-9 以及您在 [] 之间放置的任何其他字符 - 这就是 ^ 开头的含义。

【讨论】:

    【解决方案2】:

    虽然这不能直接回答您的问题,但以下去除重音、变音符号等的方法可能会很方便。

        public static String RemoveAccentsAndDiacritics(this String s)
        {
            return string.Join(string.Empty,
                               s
                                   .Normalize(NormalizationForm.FormD)
                                   .Where(c => 
                                      CharUnicodeInfo.GetUnicodeCategory(c) != 
                                          UnicodeCategory.NonSpacingMark));
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 2018-06-13
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多