Java 用模式扫描整个单词
我需要用regex=\w(或所有单词)实现模式 运行程序时,程序输出应为:Java 用模式扫描整个单词,java,regex,Java,Regex,我需要用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<St
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);
}
}
}
}
...
}
公共类文档索引{
私有树映射=
new TreeMap();//存储单词及其位置
私有字符串regex=“\\w”//任何单词
/**
*扫描文档中单词及其位置的构造函数
*/
公共文档索引(扫描文档){
Pattern p=Pattern.compile(regex);//模式类:匹配单词
整数位置=0;//当前行号
//当文档有行时
//将匹配器设置为当前行
while(doc.hasNextLine()){
位置++;
Matcher m=p.Matcher(doc.nextLine());
//当当前行中有值时
//检查它们是否是单词
//如果是这样,请将它们保存到地图上
while(m.find()){
if(map.containsKey(m.group())){
map.get(m.group()).add(location);
}否则{
ArrayList=新建ArrayList();
列表。添加(位置);
map.put(m.group(),list);
}
}
}
}
...
}
将整个单词作为模式阅读的最佳方式是什么?您需要使用
\\w+
,而不是\\w
。后者将只匹配一个字符(前者,一个或多个字符)。([^]+)+
或者你可以使用这个类