2016-11-18 96 views
1

從輸入字符串我想擺脫非字母數字字符(:,-等),但保留拉丁字符。還用"-"替換空白空間" "刪除非字母數字,但保留拉丁字符

這是我的嘗試,但我不知道如何維護拉丁字符。

String title ="NEYÑO: HOW ARE YÓU MATE"; 
title = title.replaceAll("[^A-Za-z0-9 ]", "").replace(" ", "-").toLowerCase(); 
System.out.println(title); 

輸出:

neyo-how-are-yu-mate 

所需的輸出:

neyño-how-are-yóu-mate 

在此先感謝

回答

2

使用[^\p{Alnum}\s]+Pattern.UNICODE_CHARACTER_CLASS選項,以使所有Unicode字母和digts:

String title ="NEYÑO: HOW ARE YÓU MATE"; 
title = title.replaceAll("(?U)[^\\p{Alnum}\\s]+", "").replace(" ", "-").toLowerCase(); 
System.out.println(title); // => neyño-how-are-yóu-mate 

Java demo

詳細

3

您還可以使用\p{IsLatin} character property在Java中檢測到拉丁字符:

String title ="NEYÑO: HOW ARE YÓU MATE"; 
title = title.replaceAll("(?!\\p{IsLatin})[^A-Za-z0-9 ]", "").replace(" ", "-").toLowerCase(); 
System.out.println(title); 

//=> neyño-how-are-yóu-mate 

(?!\\p{IsLatin})[^A-Za-z0-9 ]將匹配任何非字母數字或空格字符這不是一個拉丁字符。