2
String text;
System.out.println(text);

在控制台中它看起来像这样:

The US.....................................
Illinois Commerce .......... ..............
...........................................
..........................Illinois Commerce 

我需要摆脱第二个子字符串Illinois Commerce


这是我尝试过的:

text = text.replaceAll("(?:Illinois Commerce:.*?){2}", "");

我明白了java.lang.ArrayIndexOutOfBoundsException: 1

4

4 回答 4

5

你可以试试这个:

text = text.replaceFirst("(Illinois Commerce(?s).*?)Illinois Commerce", "$1");
于 2013-10-12T17:17:30.250 回答
3

假设它后面是空格或字符串的结尾,应该这样做。

text = text.replaceAll("Illinois Commerce(?= ?$)", "");

或者以下将适用于这种情况。

text = text.replaceAll("\bIllinois Commerce\s*$", "");
于 2013-10-12T17:17:57.307 回答
2

我不会为此使用正则表达式。我会做的是:

  • 找到第一次出现的索引"Illinois Commerce"
  • 获取从index + 1直到结束的子字符串。
  • 替换该"Illinois Commerce"子字符串中的 。这将确保我不会替换第一次出现,因为它不会在此子字符串中完全可用。
  • 然后将字符串的第一部分与生成的子字符串连接起来。

这就是代码的样子:

int index = text.indexOf("Illinois Commerce");      
String result = text.substring(0, index + 1) + 
                text.substring(index + 1).replace("Illinois Commerce", "");     
System.out.println(result);

  • text.substring(0, index + 1)将字符串直到I第一个Illi....

  • text.substring(index + 1)将从l第一个开始Illi....直到字符串的结尾。因此,唯一要替换的字符串是第二次出现。

于 2013-10-12T17:18:15.450 回答
1

由于只有两次出现,lastIndexOf在这种情况下可能比正则表达式更好。

无论如何,下面是正则表达式和lastIndexOf方法。

public static void main(String[] args) {

    String test = "The US.....................................\n" +
       "Illinois Commerce .......... ..............\n" +
       "...........................................\n" +
       "..........................Illinois Commerce \n";
    String toFind = "Illinois Commerce";

    System.out.print("regex\n");
    System.out.println(test.replaceAll( "(?s)^(.*)"+toFind+"(.*)$", "$1$2" )); 

    System.out.print("\nlastIndexOf\n");
    int start = test.lastIndexOf(toFind);
    System.out.println( test.substring( 0, start)
            + test.substring(start+toFind.length())); 
}
于 2013-10-12T17:26:09.243 回答