我的java项目有问题,我没有添加匹配组合,我有一个字典和混合,字典是非正常的单词,在混合中从字典改变了;在dic。 =“mouse”mixed =“usemo”那些是同一个词,我想做的如果我在混合的“usmo”程序上写下去字典,4个字母在字典上是相同的,所以word是mouse,或者mixed =“usem “字典可以改变”鼠标“,我可以用正则表达式搜索这个,但我不知道如何做到这一点,任何人都可以帮助我吗?
答案 0 :(得分:0)
这是运行代码,它将与您使用正则表达式搜索的模式匹配,并从字典中打印匹配结果。
public class RegexTestStrings {
private static HashSet<String> dictionarySet = new HashSet<String>();
private static HashSet<String> regExSetSet = new HashSet<String>();
public static void main(String[] args) {
dictionarySet.add("mouse");
dictionarySet.add("tiger");
dictionarySet.add("monkey");
RegexTestStrings regexTestStrings=new RegexTestStrings();
System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usemo"));
System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usem"));
System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"usmo"));
System.out.println(regexTestStrings.fidMatchingWord(dictionarySet,"kmoy"));
}
private String fidMatchingWord(HashSet<String> dictionarySet2, String searchWord) {
String result=null;
Iterator<String> dictionarIterator=dictionarySet.iterator();
while(dictionarIterator.hasNext()){
regExSetSet.clear();
String inputString=dictionarIterator.next();
findAllRegEx(inputString.toCharArray(), 0, inputString.length()-1);
Iterator<String> resultIterator=regExSetSet.iterator();
// Regular expression to match the pattern of search string
String pattern = "(?s)^(" + Pattern.quote(searchWord) + ".*$|.*" + Pattern.quote(searchWord) + ")$";
while(resultIterator.hasNext()){
String str=resultIterator.next();
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
boolean b = m.matches();
if(b){
result=inputString;
break;
}
}
}
return result;
}
public static void findAllRegEx(char[] ary, int startIndex, int endIndex) {
if(startIndex == endIndex){
regExSetSet.add(String.valueOf(ary));
}else{
for(int i=startIndex;i<=endIndex;i++) {
swap(ary, startIndex, i );
findAllRegEx(ary, startIndex+1, endIndex);
swap(ary, startIndex, i );
}
}
}
public static void swap(char[] arr, int x, int y) {
char temp = ary[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
Output
______________
mouse
mouse
mouse
monkey