假设您只想根据公共子字符串建议通配符模式,您可以使用最长公共子字符串算法来计算所有公共子字符串,然后根据它们的长度和出现次数选择一些。这可以递归地完成以找到更常见的子字符串。
此示例对最长的公共子字符串进行 2 次迭代并输出结果:
import java.util.*;
public class Main {
private static String longestCommonSubstring(String S1, String S2)
{
int Start = 0;
int Max = 0;
for (int i = 0; i < S1.length(); i++)
{
for (int j = 0; j < S2.length(); j++)
{
int x = 0;
while (S1.charAt(i + x) == S2.charAt(j + x))
{
x++;
if (((i + x) >= S1.length()) || ((j + x) >= S2.length())) break;
}
if (x > Max)
{
Max = x;
Start = i;
}
}
}
return S1.substring(Start, (Start + Max));
}
public static SortedMap<String,Integer> commonSubstrings(List<String> strings) {
SortedMap<String,Integer> subs = new TreeMap<>();
for (String str1: strings) {
for (String str2: strings) {
if (str1 != str2) {
String sub = longestCommonSubstring(str1,str2);
if (subs.containsKey(sub))
subs.put(sub,subs.get(sub)+1);
else
subs.put(sub,1);
}
}
}
return subs;
}
public static void main(String[] args) {
List<String> filenames = Arrays.asList(
"ABC_348093423.csv",
"i.ABC_348097340.csv",
"ABC_348099322.csv",
"i.GHI_348099324.csv",
"p.ABC_348101632.csv",
"DEF_348101736.csv",
"p.ABC_348101633.csv",
"ABC_348102548.csv");
Map<String,Integer> substrings = commonSubstrings(filenames);
Map<String,Integer> subsubstrings = commonSubstrings(new ArrayList<>(substrings.keySet()));
List<Map.Entry<String,Integer>> results = new ArrayList<>(subsubstrings.entrySet());
Collections.sort(results, (a,b) -> a.getValue().compareTo(b.getValue()));
for ( Map.Entry<String,Integer> s: results ) {
System.out.println(s.getKey() + "\t" + s.getValue());
}
}
}
当然,这会遗漏所有文件名共有的较短子字符串,例如.csv