比较字符串时如何忽略所有特殊字符?
我已设置代码以忽略字母大小写,但我还需要忽略除字母之外的所有其他字符。
到目前为止,这是我的代码
Collections.sort(MusicPlayerService.songNamesAll, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
答案 0 :(得分:0)
用空字符替换字母数字以外的字符,然后比较字符串,如:
Collections.sort(MusicPlayerService.songNamesAll, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
s1 = s1.replaceAll("[^a-zA-Z0-9]+","");
s2 = s2.replaceAll("[^a-zA-Z0-9]+","");
return s1.compareToIgnoreCase(s2);
}
});