Java的字符串.replaceFirst不起作用,我不知道它是一个错误还是我做错了

时间:2012-10-24 16:53:19

标签: java string replace

好的我有一个替换文本的方法,当我使用string.replace()它可以工作但是当我切换到relpaceFirst(),如下所示它不再有效,我在做错了什么或在这里丢失?

private void acceptAccButtonActionPerformed(java.awt.event.ActionEvent evt) {      
    int selectedAcTableItem = validAcTable.getSelectedRow();
    int selectedSugTableItem = suggestedAcTable.getSelectedRow();
    if (selectedAcTableItem > 0) {
        String acNameDefthmlText = htmlText;
        String parensName = "";
        String acName = validAcTable.getValueAt(selectedAcTableItem, 0).toString();
        String acDef = validAcTable.getValueAt(selectedAcTableItem, 1).toString();
        String acSent = validAcTable.getValueAt(selectedAcTableItem, 2).toString();
        StringBuilder acBuilder = new StringBuilder(acDef);
        acBuilder.append(" (").append(acName).append(")");            
        if (!acDef.equals("")) {
            parensName = " (" + acName + ")";
            if (htmlText.contains(acName) && !htmlText.contains(acBuilder)){
                String acReplace = acBuilder.toString();
                String acOrigDefName = acDefRow + parensName;
                if (htmlText.contains(acOrigDefName) && parensName.contains(acOrigName)){
                    acNameDefthmlText = htmlText.replaceFirst(acOrigDefName, acReplace);
                } else if (htmlText.contains(acName)) {
                    acNameDefthmlText = htmlText.replaceFirst(acName, acReplace);
                }
                htmlText = acNameDefthmlText;

            }                
            validAcTable.setValueAt(true, selectedAcTableItem, 2);
            Acronym acronym = createNewAcronym(acName, acSent, acDef, true);
            try {

                AcronymDefinitionController.sharedInstance().writeAcronymToExcelSheet(acName, acDef);
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            } catch (InvalidFormatException ex) {
                Exceptions.printStackTrace(ex);
            }
            if (validAcTable.getRowCount() - 1 >= validAcTable.getSelectedRow() + 1) {
                validAcTable.changeSelection(selectedAcTableItem + 1, 0, true, true);
            }
            validAcTable.repaint();
        }
    }

1 个答案:

答案 0 :(得分:3)

如果您注意到有两种方法的签名:

replace(char oldChar,char newChar);
replace(CharSequence target, CharSequence replacement);

replaceFirst(String regex, String replacement);

正如您所看到的,在replaceFirst中,您匹配的参数被视为regex(正则表达式),如果参数中包含任何特殊字符,这将导致差异。

例如:请考虑以下内容:

System.out.println("abcdab".replace("ab", "ef"));  //<- replaces all
System.out.println("abcdab".replaceFirst("ab", "ef"));//<-replaces first
System.out.println("\\abcdab".replace("\\ab", "ef")); //<-replaces first
System.out.println("\\abcdab".replaceFirst("\\ab", "ef"));
//^ doesn't replace as `\` is an special char