nonac
nonac

Reputation: 35

replaceAll - Java

I have this output [4,-3],[-3,-1],[2,-4],[-4,1] and this is the code that gives me this output:

public static String[] arg() throws IOException {
    String prova =getString().replaceAll(" 0","] [");
    String prova1=prova.replaceFirst("0","[");
    String prova2=prova1.replaceAll("%0","]");
    String prova3=prova2.replaceAll(" ",",");
    String prova4=prova3.replaceAll("],["," ");
    System.out.println(prova4);
    String[] strArray = getString().split(" ");

    //System.out.println(Arrays.toString(strArray));
    return strArray;

}

My problem is that I would have as output this [4,-3] [-3,-1] [2,-4] [-4,1] that is, a blank space in place of this ],[. I think that String prova4=prova3.replaceAll("],["," "); should do this, but it produce several error.

This is the error: Unclosed character class near index 2 ],[

Upvotes: 0

Views: 1613

Answers (4)

lpiepiora
lpiepiora

Reputation: 13749

You solution doesn't work because the first argument to the replaceAll is a regular expression. The characters [ and ] have a special meaning, as described here:

Character classes
[abc]           a, b, or c (simple class)
[^abc]          Any character except a, b, or c (negation)
[a-zA-Z]        a through z or A through Z, inclusive (range)
[a-d[m-p]]      a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]]    d, e, or f (intersection)
[a-z&&[^bc]]    a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]   a through z, and not m through p: [a-lq-z](subtraction)

You have to escape them so the code looks like this replaceAll("\\],\\[", "] ["). However I don't think that in your case that you need to use replaceAll, as you may use replace(), which will yield cleaner code replace("],[", "] [").

Upvotes: 1

Rakesh KR
Rakesh KR

Reputation: 6527

From Doc

There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash.

Therefore what you need to try with : \\]

Upvotes: 1

Farvardin
Farvardin

Reputation: 5414

use this :

String prova4=prova3.replaceAll(","," ");

Upvotes: 1

Mike B
Mike B

Reputation: 5451

The issue is that replaceAll() expects a regex pattern, not a string literal. [ and ] have special meanings in regex patterns, they group character classes. You can fix your problem by escaping the [ and ]:

String prova4 = prova3.replaceAll("\\],\\[", " ");

To get the output you want though, you need to only replace the comma, not the brackets:

String prova4 = prova3.replaceAll("\\],\\[", "\\] \\[");

Upvotes: 2

Related Questions