【问题标题】:Checking the string character if it does not match it will replace [closed]检查字符串字符是否不匹配将替换[关闭]
【发布时间】:2016-06-10 06:47:36
【问题描述】:

我想搜索一个字符串,即使格式不匹配例如 “Apple”是我要搜​​索的字符串,但我输入了“apple”或“áapple”或“Apple”。我想检查我输入的每个字符, 如果它与我试图搜索的字符串不匹配,它将替换它,直到我得到字符串“Apple”。

【问题讨论】:

  • 这毫无意义。只需强制用户输入 Apple,因为无论如何您都会替换它。
  • @user3659052 我的教授说这将使搜索更加用户友好。像谷歌一样,如果你拼错了单词,它会纠正拼错的单词并给你正确的答案。但任何建议都会很好

标签: java regex char


【解决方案1】:

您可能对以下代码感兴趣,该代码使用java.text.Normalizer 在较大的规范化字符串中查找规范化字符串:

该类提供了normalize 方法,它将Unicode 文本转换为等效的组合或分解形式,从而可以更轻松地对文本进行排序和搜索。 normalize 方法支持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;
        }

    }
}

【讨论】:

  • 这与我想要做的非常接近。谢谢! @Wiktor Stribiżew 我正在使用 Sqlite 并且我正在获取名称的数据,即使用户试图搜索错误的输入,它仍然会为您提供最接近的数据。
  • 如果 closest 表示 similar,您应该真正开始寻找基于 Levenstein 距离的解决方案。如果您只对无变音符号比较感兴趣,我的解决方案就足够了。
  • 我认为它对我来说太复杂了。我只是一个初学者,我正在做一个硬编码的开关盒。有什么基本的建议吗? @Wiktor Stribiżew
  • 您的问题现已结束。要重新打开它,您需要使用您的非工作代码对其进行更新,并解释究竟什么不工作以及它应该如何工作。
【解决方案2】:

您的问题并不完全清楚,但听起来您可能正在尝试计算两个字符串之间的 Levenshtein 距离。如果您对该术语进行一些研究,则应该清楚这是否是您所需要的。

简而言之:

Levenshtein 距离是将“ápple”转换为“Apple”所需的删除、插入或替换的数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多