TheBook
TheBook

Reputation: 1708

Java PatternSyntaxException when replacing characters in a String object

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("]", "");

Upvotes: 1

Views: 61

Answers (2)

tavnab
tavnab

Reputation: 2734

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();

Upvotes: 1

Mureinik
Mureinik

Reputation: 311948

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("]", "");

Upvotes: 2

Related Questions