我正在尝试编写一种方法来扫描字符串中的某些字符,并报告找到了哪些(如果有的话):
// Special characters are ~, #, @, and *
// If text == "Hello~Clarice, you're s#o ambitious", then this
// method should return a string == "~#". If no special characters
// found, return null. If the same special character occurs 2+ times,
// ignore it and do not return strings with duplicate special chars, like
// "##@***", etc. --> just "#@*".
public String detectAndGetSpecialCharacters(String text) {
Pattern p = Pattern.compile("[~#@*]");
Matcher m = pattern.matcher(text);
String specialCharactersFound = null;
if(m.find()) {
// ???
}
return specialCharactersFound;
}
我已经完成了这个方法的检测部分,但我正在努力寻找一种有效/优雅的方法Matcher
来告诉我找到了哪些特殊字符,此外,将它们连接在一起(删除重复项!)并返回它们。提前致谢!