在列表中存储模式匹配的索引

Store Index of Pattern Match in List

尝试使用正则表达式将一个词与一行文本匹配,并将所有匹配词的第一个字符的索引存储在列表中,以便在我打印后的下一行定位标识符(“^”)匹配线。我收到以下错误:

H:\CSCI 1152 笔记>javac Project.java .\FindWord.java:17: 错误:类型不兼容:字符串无法转换为列表 indexOfSearch = matcher.group(); ^

public String findWords(String str, String search) throws Exception {

        try {
            List<Integer> indexOfSearch = new ArrayList<>();

            Pattern pattern = Pattern.compile("\b" + search + "\b");
            Matcher matcher = pattern.matcher(str);

            while (matcher.find()) {
                indexOfSearch = matcher.group();
            }

            String fullCarets = "";
            System.out.println(str);//print the text from file
            if(indexOfSearch.size() >= 1) {            
                for (int j = 0; j <= indexOfSearch.size() - 1; j++) {//each index of search word
                    String spaces = "";//spaces to caret
                    int indexTo = 0;//how many spaces will be added
                    if (j < 1 && indexOfSearch.get(j) != -1) {
                        indexTo = indexOfSearch.get(j);//the first index
                    } else if (indexOfSearch.get(j) != -1) {
                        indexTo = (indexOfSearch.get(j) - indexOfSearch.get(j - 1) - 1);//all other indexes in the row
                    }
                    if (indexTo >= 0 && indexOfSearch.get(j) != -1) {                   
                        for (int i = 0; i < indexTo; i++) {//add appropriate number of spaces to word  
                            spaces += " ";//add a space
                        }
                        fullCarets += (spaces + "^");
                        System.out.print(spaces + "^");//print the spaces and spaces
                    }
                }

                System.out.println("");//used to make the print slightly easier to look at.

                return str + "\n" + fullCarets + "\n";

            }
            return "";
        }catch (Exception e) {

            throw new Exception(e.getMessage());
        }

您有一条编译器错误消息:

error: incompatible types: String cannot be converted to List

这一行:

indexOfSearch = matcher.group();

group()returns一个String,而indexOfSearch定义为:

List<Integer> indexOfSearch = new ArrayList<>();

很明显这是方孔中的圆钉。你在这里做错了几件事。首先,您试图分配给 List 变量,而实际上您想要 add() 分配给该变量引用的 List。其次,List 被声明为保存 Integer 值,而不是 String 值,因此您需要添加其他内容,而不是 matcher.group()。从您的问题描述和变量名来看,您似乎想要匹配项 start() 的索引。

indexOfSearch.add( matcher.start() );