3

I have the following String text:

/Return/ReturnData/IRS1040/DependentWorksheetPP[1]/DependentCodePP

I'd like to strip off the [1] index so I just have:

/Return/ReturnData/IRS1040/DependentWorksheetPP/DependentCodePP

How can I accomplish this in Java?

string.replaceAll("[?]","");

This doesn't seem to work.

Any help or info would be much appreciated

mosawi
  • 1,283
  • 5
  • 25
  • 48
  • 1
    Strings are immutable in Java, 'replaceAll' will return a new string that has the replacements. See [String.replaceAll](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)). Possible duplicate: http://stackoverflow.com/questions/10951333/why-isnt-the-string-value-changed-after-string-replace-in-java. Is this the issue you're having? – Xiao Nov 05 '15 at 04:59
  • Replace `\[\d+\]` by empty string – Tushar Nov 05 '15 at 05:00

2 Answers2

5

First, in Java, String is immutable (so be sure to assign the result of replaceAll). Next, the [ and ] are meaningful in a regular expression (escape them). And \\d+ is one or more digit. Something like,

String str = "/Return/ReturnData/IRS1040/DependentWorksheetPP[1]/"
    + "DependentCodePP";
str = str.replaceAll("\\[\\d+\\]", "");
System.out.println(str);

Output is

/Return/ReturnData/IRS1040/DependentWorksheetPP/DependentCodePP
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3
string.replaceAll("\\[.*?\\]","");

You need to escape [] as they are special characters in regex.

vks
  • 67,027
  • 10
  • 91
  • 124