Reputation: 338
I am trying to write an array to a text file, and in the process I have noticed that arrays are written in the format of: [1, 1, 2, 2]
(an example of an int array) and I want to convert an array, take the int array above as an example, convert it to a string and remove the [
and ,
from it. How can I go about doing it, I've tried looking for a string pattern I could write and had no luck, I have also tried writing:
char [] PIN = System.console().readPassword();
String pin = java.util.Arrays.toString(PIN);
String WriteToF = pin.replaceAll("[", "");
but get the following error:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed char
acter class near index 0
[
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
Also what kind of a character is [
classed as in Java in terms of These patterns?
Upvotes: 0
Views: 70
Reputation: 174776
In regex [
is considered as a special meta character(start of a charcter class). To match a literal [
, you need to escape [
symbol when passing it to replaceAll
function.
String WriteToF = pin.replaceAll("\\[", "");
When the regex engine see a [
character then it considered it as a start of a character class. If a character class is opened then it must be closed using ]
(]
means the end of character class.).
so that only you get the below error.
Unclosed character class near index 0
Upvotes: 0
Reputation: 588
replaceAll("\\[", "")
instead.[
is to represent the beginner of Character classes, which need to be escaped when matching [
literally.Upvotes: 0
Reputation: 12558
The String#replaceAll
method replaces using regex. If you want to replace the literal [
character, you should use the String#replace
method:
String WriteToF = pin.replace("[", "");
In regex, the [
character marks the beginning of a character class. You need to close the character class with ]
for it to be valid regex syntax. If you wanted to replace the literal [
character with regex, you would escape it: "\\[
".
Upvotes: 2