java - 使用 Pattern 扫描整个单词

标签 java regex

我需要使用正则表达式=\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);
                }
            }
        }
    }
...
}

将整个单词作为模式来阅读的最佳方法是什么?

最佳答案

您需要使用\\w+,而不是\\w。后者仅匹配一个字符(前者匹配一个或多个字符)。

关于java - 使用 Pattern 扫描整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239629/

相关文章:

java - 如何在 API 23+ 中解析 setLatestEventInfo

java - 从 Java 中的方法打印数组

java - 如何以编程方式执行 p2 安装

regex - Vim 匹配一个矩形区域

java - 从文件路径创建位图/可绘制对象

java - JSON 到 Android 错误

java - VBScript:正则表达式匹配不正确的注册表值时出错

ruby - 使用正则表达式腾出空间

regex - TCL Regex 用于匹配 CSV 中的未转义引号

python - 在 python 中是否有等效于 emacs 的 rx 宏?