Ruchira
Ruchira

Reputation: 1

How to split a string having [] as delimiters in java

I want to remove [ ] braces from the below string- "[maths=100, english=20]"

I have tried doing it in following ways but in both the trials it is not removing the end ] brace.

Approach 1:

String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[");
String[] finalValue = value[1].split("\\]");
System.out.println(finalValue[0]);  // this should give string as maths=100, english=20

Approach 2:

String[] metrics= "[maths=100, english=20]";
String[] value = metrics[1].split("\\[\\]");
System.out.println(finalValue[1]);  // this should give string as maths=100, english=20

Can anyone guide me where i am doing it wrong?

Upvotes: 0

Views: 59

Answers (3)

Couper
Couper

Reputation: 434

You can simply replace the braces like this:

String s = "[maths=100, english=20]";
s = s.replace("[", "").replace("]", "");
System.out.println(s);

Upvotes: 0

xtratic
xtratic

Reputation: 4699

If you simply want to trim and clean your data then you can do a simple check and substring.

String input = ...;
String cleanedInput = input.trim();
if (cleanedInput.startsWith("[") && cleanedInput.endsWith("]")) {
    cleanedInput = cleanedInput.substring(1, cleanedInput.length() - 1);
    System.out.println(cleanedInput);
}

If you're wanting to match and capture from a larger set of data then you can use RegEx patterns with capture groups to match and capture the data you want.

For parsing a proper document structure though you should try to use a real parser but if you truly are just trying to match and capture some simple data then RegEx will often be ok.

String input = ...;
// RegEx pattern "\[([^\[\]]*)\]" anything inside braces except other braces
Pattern pattern = Pattern.compile("\\[([^\\[\\]]*)\\]");
Matcher matcher = pattern .matcher(input);
while (matcher.find()) {
    String data = matcher.group(1);
    System.out.println(data);
}

Upvotes: 1

Greich
Greich

Reputation: 108

Try this code

String metrics= "[maths=100, english=20]";
String[] split = metrics.split("\\[|]");
System.out.println(split[1]);

it prints "maths=100, english=20"

Or you can simply replace all [ and ] character

String metrics = "[maths=100, english=20]";
metrics = metrics.replace("[", "").replace("]", "");
System.out.println(metrics);

Upvotes: 1

Related Questions