简体   繁体   English

替换String对象中的字符时出现Java PatternSyntaxException

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

replaceAll replaces all occurrences that match a given regular expression . replaceAll替换与给定正则表达式匹配的所有匹配项。 Since you just want to match a simple string, you should use replace instead: 既然你只想匹配一个简单的字符串,你应该使用replace代替:

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

To answer the main question, if you use replaceAll , make sure your 1st argument is a valid regular expression. 要回答主要问题,如果使用replaceAll ,请确保第一个参数是有效的正则表达式。 For your example, you can actually reduce it to 2 calls to replaceAll , as 2 of the substitutions are identical. 对于您的示例,您实际上可以将其减少为2次调用replaceAll ,因为其中2个替换是相同的。

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. 但是,看起来你只是试图将String列表的所有元素连接在一起。 It's much more efficient to construct this string directly, by iterating your list and using StringBuilder : 通过迭代列表并使用StringBuilder ,直接构造此字符串会更有效:

StringBuilder builder = new StringBuilder();

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

String after = builder.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM