java - 检查字符串字符,如果不匹配则替换

标签 java regex char

即使格式不匹配,我也想搜索字符串例如 “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. The normalize method supports the standard normalization forms described in Unicode Standard Annex #15 — Unicode Normalization Forms.

Sample code :

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/

相关文章:

java - InetAddress.getLocalHost() 总是返回 127.0.0.1

html - 在不同的网站使用相同的 HTML 生成奇怪的字符

Java Array Char 和 String 数组中的区别

javascript - 如何将以特定模式开头的每一行传输到字符串的末尾?

c - 使用 scanf() 从键盘读取时从先前输入读取换行符

java - HttpURLConnection getResponseCode() 不起作用

java - 如何将 java ArrayList<Double> 转换为等效的 double[]

java - maven 将我的项目编译为 Java 的哪个主要版本和次要版本?

php - 如何正确命名 bootstrap 3 以与其他未命名空间的 bootstrap 3 实例一起使用

javascript - 带有散列标签的 RegEx 问题