Dragona
Dragona

Reputation: 13

Splitting for "[" and "]" and standard escaping not working

I'm trying to split a String that may or may not contain the characters "[" and "]", and I've tried the standard Split, after putting a condition "if string contains [ or ]" but get a

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

If I use the "\[" for the Split parameter a System out says that the String is \[ and if I remove one of the \ it gives a compilation error, obviously. With \[ my simple splitting doesn't work. Adding more \ doesn't help.

I tried String x = Pattern.quote("["); and then splitting for x, but no. It doesn't work.

I'm using Java uuh... 8? Since I can put full methods into Interfaces, and Spring Framework. I don't know if it changes something, but I'm also connected to a SQL database, but data gets read, so I doubt the problem is there.

Code for the curious.

public List<String> equippableBy()
{

    List<String> list = new ArrayList<String>();
    String bracket = "\\[";
    
    if(desc.contains(bracket))
    {   
        String[] lista = desc.split(bracket);
        String[] classi = lista[1].split("-");

        for(int i = 0; i < classi.length; i++)
        {
            if(!classi[i].contains(bracket))
                list.add(classi[i]);
            else
                list.add(classi[i].split(bracket)[0]);
        }   
        return list;
    }
    else 
    {
        list.add("Not Equippable");
        return list;
    }   
}

Edit: I'm noticing problems escaping backslashes here too. I mean that a double backslash won't proprely show a single [ for splitting.

Upvotes: 1

Views: 64

Answers (1)

Unmitigated
Unmitigated

Reputation: 89364

String#contains does not accept a regular expression like String#split.

Change

if(desc.contains(bracket))

to

if(desc.contains("["))

Also, change

if(!classi[i].contains(bracket))

to

if(!classi[i].contains("["))

Alternatively, you can define bracket as a literal bracket and use Pattern.quote for splitting.

final String bracket = "[";
//...
list.add(classi[i].split(Pattern.quote(bracket))[0]);

Upvotes: 2

Related Questions