即使格式不匹配,我也想搜索字符串例如 “Apple”是我试图搜索的字符串,但我输入“apple”或“ápple”或“Apple”。我想检查我输入的每个字符, 如果它与我尝试搜索的字符串不匹配,它将替换它,直到我得到字符串“Apple”。
最佳答案
您可能对以下代码感兴趣,该代码使用 java.text.Normalizer
在较大的规范化字符串中查找规范化字符串。 :
This class provides the method
normalize
which transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text. Thenormalize
method supports the standard normalization forms described in Unicode Standard Annex #15 — Unicode Normalization Forms.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.Normalizer;
class Ideone
{
public static void main(String[] args) {
String haystack[] = {"Apple","Apple","Apple"}; // sample input strings
String needle[] = {"ápple", "apple", "Applé"}; // sample keywords
for (int i = 0; i < haystack.length; i++) { // loop through inputs
System.out.println(
find(
normalize(haystack[i]), // get the normalized form of input
normalize(needle[i]) // get the normalized form of the keyword
)
);
}
}
public static String normalize(String s) { // Get the string without diacritics
return Normalizer.normalize(s, Normalizer.Form.NFD).replaceAll("\\p{Mn}", "");
}
// Checks if a string contains another in a case-insensitive way
public static boolean find(String haystack, String needle) {
Pattern p = Pattern.compile(needle, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(haystack);
if (m.find()) {
return true;
} else {
return false;
}
}
}
关于java - 检查字符串字符,如果不匹配则替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35662127/