c# - 如何按 X% 匹配 2 个字符串(即 >90% 匹配)

标签 c# java javascript regex

例如:

S1: "some filename contains few words.txt"
S2:“一些文件名包含几个单词 - draft.txt”
S3:“一些文件名包含几个单词 - 另一个 draft.txt”
S4: "some filename not contains few words.txt"

重要的是要注意,我可以为第一个字符串获取 S2 或 S3,并匹配其他字符串。

已编辑:我有“master”字符串,我需要找到匹配项。

比方说,在第一轮中,我发现了拼写错误。

现在我只需要匹配整个单词。

我希望能够确定 7 个单词中有 5 个匹配,或者 10 个单词中有 7 个匹配。“Y 中的 X”的确切数量不太重要。

重要的是如何找出 X 个单词的不同之处,无论它们在句子中的位置如何。

谢谢

最佳答案

这不是正则表达式问题。

您没有指定语言,但如果您使用的是 java,则有 getLevenshteinDistance StringUtils 的方法。来自 javadocs:

Find the Levenshtein distance between two Strings.

This is the number of changes needed to change one String into another, where each change is a single character modification (deletion, insertion or substitution).

用法:

int distance = StringUtils.getLevenshteinDistance(
    "some filename contains few words.txt",
    "some filename not contains few words.txt"
);

要按一定百分比匹配,您必须决定哪个字符串是“主”,因为输入字符串可以有不同的长度:distance 可能是所有删除,所以 "cat ""白内障" 的距离为 5。定义什么是“90% 匹配”也有点困难。看看我们的 cat 例子; 100% 的字符串“cat”都在“cataract”中找到,但它们并不完全相同。您必须根据您的用例来决定这些规则。

更新

如果您的“差异”应该是基于单词的,那么在单词边界上拆分字符串并从生成的单词构造一个 Map 到每个单词的计数会相对容易。比较每个字符串生成的 map 应该会给你一个粗略的“相似性”测量。例如:

public HashMap<String, Integer> countWords(String str) {
    HashMap<String, Integer> counts = new HashMap<String, Integer>();
    for(String s : str.split("\\s+")) {
        if(!s.isEmpty()) {
            if(counts.containsKey(s)) {
                counts.put(s, counts.get(s) + 1);
            } else {
                counts.put(s, 1);
            }
        }
    }
    return counts;
}

// ...

String s1 = "some filename contains few words.txt";
String s2 = "some filename not contains few words.txt";
HashMap<String, Integer> s1Counts = countWords(s1);
HashMap<String, Integer> s2Counts = countWords(s2);
// assume s1 is "master" string, count the total number of words
int s1Total = 0, s2Total = 0;
for(Integer i : s1Counts.values()) {
    s1Total += i;
}
// iterate over words in s1, find the number of matching words in s2
for(Map.Entry<String, Integer> entry : s1Counts.entrySet()) {
    if(s2Counts.containsKey(entry.getKey())) {
        if(s2Counts.get(entry.getKey()) >= entry.getValue()) {
            s2Total += entry.getValue();
        } else {
            s2Total += s2Counts.get(entry.getKey());
        }
    }
}
// result
System.out.println(s2Total + " out of " + s1Total + " words match.");

关于c# - 如何按 X% 匹配 2 个字符串(即 >90% 匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11114651/

相关文章:

c# - 如何使用 makecert 创建自签名证书

java - 是否可以将两条线视为一条线?

c# - Silverlight 应用程序中的字符串本地化问题

c# - LINQ lambda 表达式替换字符串中的多个字符?

C# 更改 FlowLayoutPanel 中控件的位置

java - 具有类特定属性的最佳解决方案

java - 在单例类中并发调用方法

javascript - 流程图 : change the axis data type to time

Javascript switch 语句不起作用 - 三个太多了吗?

javascript - Chrome DevTools 搜索网站中的所有 javascript 文件