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

时间:2017-12-02 02:26:31

标签: java delimiter

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

H:\ CSCI 1152说明> javac Project.java 。\ FindWord.java:17:错误:不兼容的类型:字符串无法转换为List                                 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());
        }

1 个答案:

答案 0 :(得分:1)

您有编译错误消息:

  

错误:不兼容的类型:字符串无法转换为List

在这一行:

indexOfSearch = matcher.group();

group()返回StringindexOfSearch定义为:

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

很明显,这是一个方孔中的圆钉。你在这里犯了一些错误。首先,您尝试分配到List变量,实际上您希望add()到该变量引用的List。其次,List被声明为保留Integer值,而不是String值,因此您需要添加其他内容,而不是matcher.group()。从您的问题描述和变量名称看起来您想要匹配的start()的索引。

indexOfSearch.add( matcher.start() );