用于生成 slug 的 Java 代码/库(用于漂亮的 URL) [英] Java code/library for generating slugs (for use in pretty URLs)

查看:69
本文介绍了用于生成 slug 的 Java 代码/库(用于漂亮的 URL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 和 Django 等 Web 框架内置了对slugs"的支持,用于生成可读且对 SEO 友好的 URL:

Web frameworks such as Rails and Django has built-in support for "slugs" which are used to generate readable and SEO-friendly URLs:

slug 字符串通常只包含字符 az0-9-,因此可以在没有 URL 转义的情况下编写(想想foo%20bar").

A slug string typically contains only of the characters a-z, 0-9 and - and can hence be written without URL-escaping (think "foo%20bar").

我正在寻找一个 Java slug 函数,它给定任何有效的 Unicode 字符串都将返回一个 slug 表示(az0-9-).

I'm looking for a Java slug function that given any valid Unicode string will return a slug representation (a-z, 0-9 and -).

一个简单的 slug 函数类似于:

A trivial slug function would be something along the lines of:

return input.toLowerCase().replaceAll("[^a-z0-9-]", "");

然而,这个实现不会处理国际化和重音(ë > e).解决此问题的一种方法是枚举所有特殊情况,但这不会很优雅.我正在寻找更深思熟虑和更通用的东西.

However, this implementation would not handle internationalization and accents (ë > e). One way around this would be to enumerate all special cases, but that would not be very elegant. I'm looking for something more well thought out and general.

我的问题:

  • 在 Java 中生成 Django/Rails 类型 slug 的最通用/最实用的方法是什么?

推荐答案

规范化你的字符串使用规范分解:

Normalize your string using canonical decomposition:

  private static final Pattern NONLATIN = Pattern.compile("[^\w-]");
  private static final Pattern WHITESPACE = Pattern.compile("[\s]");

  public static String toSlug(String input) {
    String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
    String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
    String slug = NONLATIN.matcher(normalized).replaceAll("");
    return slug.toLowerCase(Locale.ENGLISH);
  }

不过,这仍然是一个相当幼稚的过程.它不会对 s-sharp(ß - 在德语中使用)或任何非拉丁字母(希腊语、西里尔字母、CJK 等)做任何事情.

This is still a fairly naive process, though. It isn't going to do anything for s-sharp (ß - used in German), or any non-Latin-based alphabet (Greek, Cyrillic, CJK, etc).

更改字符串的大小写时要小心.大小写形式取决于字母表.在土耳其语中,U+0069 (i) 的大写是 U+0130 (İ),而不是 U+0049 (I) 因此,如果您在土耳其语语言环境下使用 String.toLowerCase(),您可能会在字符串中引入一个非 latin1 字符.

Be careful when changing the case of a string. Upper and lower case forms are dependent on alphabets. In Turkish, the capitalization of U+0069 (i) is U+0130 (İ), not U+0049 (I) so you risk introducing a non-latin1 character back into your string if you use String.toLowerCase() under a Turkish locale.

这篇关于用于生成 slug 的 Java 代码/库(用于漂亮的 URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆