2017-11-14 4 views
0

私は私のJavaプロジェクトに問題がある、私はマッチの組み合わせを追加しなかった、私は辞書と混在している、辞書は普通の言葉であり、 dicで= "mouse" mixed = "usemo"それらは同じ単語です、私はしたいです。私は混合usmoプログラムで辞書に行き、4文字は辞書で同じですので、単語はマウスです、またはmixed = "usem "辞書は"マウス "を変更することができます、私は正規表現でこれを可能にすることができます検索しますが、私はこれを行う方法については考えていない誰も私を助けることができます??どのように私はJavaの正規表現を行うことができますか? 2-3文字を一致させる?

+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 
+0

ıこれを試しましたが、同じような機能はありますか?私のプログラムはこれほど短いわけではないので、たくさんの単語のインミープログラムがあります。 –

+0

私は3文字が大丈夫、辞書からの変更は同等であることを意味します。 –

+0

@FurkanKesgin、もしあなたがSQLの 'like'関数を探しているのであれば、Javaの'。* 'は上記でパターンの中で使ったREGEXの文字と一致します。あなたの要件をサポートするために上記のプログラムを修正しなければなりません。私は答えがあなたが最初に尋ねた質問を満足させていると信じています。あなたが別の問題に直面しているなら、新しい質問を作成して問題を説明してください。 – utpal416

関連する問題