2012-04-20 12 views
0

パターンを正規表現= \ w(またはすべての単語)で実装する必要があります。私は実行するとパターンで全体の単語をスキャンする

プログラムの出力は次のようになります。

a [1] 
is [1] 
test[1,2] 

ではなく、それは次のようになります。

a [1] 
e [2] 
h [1] 
i [1, 1] 
s [1, 1, 2] 
t [1, 2, 2] 

スキャンとパターンマッチングのためのコードの責任がは以下の通りです:

public class DocumentIndex { 

    private TreeMap<String, ArrayList<Integer>> map = 
    new TreeMap<String, ArrayList<Integer>>();  // Stores words and their locations 
    private String regex = "\\w";    //any word 

    /** 
    * A constructor that scans a document for words and their locations 
    */ 
    public DocumentIndex(Scanner doc){ 
    Pattern p = Pattern.compile(regex);  //Pattern class: matches words 
    Integer location = 0;     // the current line number 
     // while the document has lines 
     // set the Matcher to the current line 
     while(doc.hasNextLine()){ 
      location++; 
      Matcher m = p.matcher(doc.nextLine()); 
      // while there are value in the current line 
      // check to see if they are words 
      // and if so save them to the map 
      while(m.find()){ 
       if(map.containsKey(m.group())){ 
        map.get(m.group()).add(location); 
       } else { 
        ArrayList<Integer> list = new ArrayList<Integer>(); 
        list.add(location); 
        map.put(m.group(), list); 
       } 
      } 
     } 
    } 
... 
} 

言葉全体をパターンとして読む最も良い方法は何ですか?

答えて

2

\\w+ではなく、\\wを使用する必要があります。後者は、1つの文字(前者、1つ以上の文字)にのみ一致します。

関連する問題