Alpha
Alpha

Reputation: 14066

Unable to replace [ with {

I'm trying to replace [ with { in java with following code:

String expectedTimeCriteria = "Month Days=" + monthDays.toString().replaceAll("[", "{");

but this throws following error:

 java.util.regex.PatternSyntaxException: Unclosed character class near index 0 [
                                                                               ^

Could you please help me understand what went wrong here?

Upvotes: 0

Views: 97

Answers (4)

eztam
eztam

Reputation: 3841

You have to ecape the [ character with \\[

String expectedTimeCriteria = "Month Days=" + monthDays.toString().replaceAll("\[", "{");

Upvotes: 0

H. Fong
H. Fong

Reputation: 11

String.replaceAll() takes 2 arguments, the regex and the replacement string. When you pass in "[" as the regex, Java tries to compile it as a regular expression and expects to see the closing "]". That's why you are getting

java.util.regex.PatternSyntaxException: Unclosed character class near index 0 [

You need to escape the character "\[" and this should work.

Upvotes: 1

ninja.coder
ninja.coder

Reputation: 9658

Use replace() instead of replaceAll() as replaceAll() is used with the Regex and [ carries a special meaning in the Regex.

replace() on the other hand takes a String and performs the same function as that of replaceAll().

Corrected Code Snippet:

String expectedTimeCriteria = "Month Days=" + monthDays.toString().replace("[", "{");

Alternatively, you can use the escape character as follows:

String expectedTimeCriteria = "Month Days=" + monthDays.toString().replaceAll("\\[", "{");

Upvotes: 1

SomeJavaGuy
SomeJavaGuy

Reputation: 7357

String#replaceAll does use regex, so you are having a sematic error for the regex syntax in this case. If you do just want to replace all [ with { you could just use the String#replace method, which doesn´t use regex and would still replace each occurence of the searched string.

monthDays.toString().replace("[", "{");

Upvotes: 2

Related Questions