简体   繁体   中英

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?

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);
}

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);

You can simply replace the braces like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM