该方法应该只允许URI字符串中的“0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-
”字符。
这就是普遍的共识:
string = string.toLowerCase();
string = Normalizer.normalize(string, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
-
保留非字母数字字符,并在必要时崩溃。
string = string.replaceAll("[^\\p{Alnum}]+", "-");
总结如下:
public static String toPrettyURL(String string) {
return Normalizer.normalize(string.toLowerCase(), Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.replaceAll("[^\\p{Alnum}]+", "-");
}
以下正则表达式将与您的算法完全相同。我不知道做这类事情的图书馆。
String s = input .replaceAll(" ?- ?","-") // remove spaces around hyphens .replaceAll("[ ']","-") // turn spaces and quotes into hyphens .replaceAll("[^0-9a-zA-Z-]",""); // remove everything not in our allowed char set
如果您想搜索更多信息,这些通常称为“slu”。
您可以查看其他答案,例如How can I create a SEO friendly dash-delimited url from a string?和How to make Django slugify work properly with Unicode strings?
它们比javascript更多地涵盖了C#和Python,但是对于slug约定以及制作它们时可能遇到的问题(例如唯一性,unicode规范化问题等)有一些与语言无关的讨论。