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);
                }
            }
        }
    }
...
}

単語全体をパターンとして読み取る最良の方法は何ですか?

4

2 に答える 2

2

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

于 2012-04-20T02:57:19.613 に答える
0

([^ ]+)+

または、 StringTokenizerクラスを使用できます。

于 2012-04-20T03:31:12.737 に答える