1

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.

I have tried the following but I am geting the error in the title. Simple:

[06:15, 06:45, 07:16, 07:46]

Result should look as this:

06:15 06:45 07:16 07:46

Code:

List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll("  ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
2
  • Ok I found the answer String after = timeEntries.replace(",", " ").replace("[","").replace("]","").replace(" "," "); Commented Jun 10, 2015 at 22:14
  • In regex (the argument you pass to replaceAll is a regex), [ and ] must be escaped. Especially in Java. Commented Jun 10, 2015 at 22:16

2 Answers 2

2

replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:

List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace("  ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
Sign up to request clarification or add additional context in comments.

Comments

1

To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.

List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");

But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:

StringBuilder builder = new StringBuilder();

for (String timeEntry: entry.getValue()) {
  builder.append(timeEntry);
}

String after = builder.toString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.