dumb_coder
dumb_coder

Reputation: 325

java regex with curly braces

I am having hard time solving this particular problem

input: [{"acks":"6"},{"acks":"7"},{"acks":"8"}]
regex: [\{]*["acks:"]
current output: [6},7},8}]
desired output: [6,7,8]

I am facing problem with the ending curly braces.

Thank you for helping me in advance!!

Upvotes: -2

Views: 91

Answers (4)

ikhot
ikhot

Reputation: 1

This should work for the described case:

System.out.println("[{\"acks\":\"6\"},{\"acks\":\"17\"},{\"acks\":\"888\"}]".replaceAll("(\\{\"acks\":\")*(\"})*", ""));

Result: [6,17,888]

I can see that there are some comments that instead of "acks" key might be any symbols, hence I would suggest to use next regexp (\{.*?:\")*(\"})* see https://regex101.com/r/kfAYsQ/1

System.out.println("[{\"key1\":\"6\"},{\"key2\":\"17\"},{\"key3\":\"888\"}]".replaceAll("(\\{.*?:\")*(\"})*", ""));

input: [{\"key1\":\"6\"},{\"key2\":\"17\"},{\"key3\":\"888\"}]

result: [6,17,888]

Upvotes: -1

Reilas
Reilas

Reputation: 6266

Just check for \"acks\", the : character, and the starting and ending " characters.

The check for { doesn't seem necessary.

\"acks\":\"(.+?)\"
String string = "{\"acks\":\"6\"},{\"acks\":\"7\"},{\"acks\":\"8\"}";
Pattern pattern = Pattern.compile("\\\"acks\\\":\\\"(.+?)\\\"");
Matcher matcher = pattern.matcher(string);
List<String> list = new ArrayList<>();
while (matcher.find()) list.add(matcher.group(1));

Output

[6, 7, 8]

Upvotes: 0

Sayan
Sayan

Reputation: 11

You can try this regexp (?:\"[\\w]+\":\")(\\d+)

import java.util.regex.*;
import java.util.*;
import java.util.function.Supplier;

class HelloWorld {
    public static void main(String[] args) {

    Pattern p = Pattern.compile("(?:\"[\\w]+\":\")(\\d+)");
    Matcher m = p.matcher("[{\"acks\":\"6\"},{\"acks\":\"7\"},{\"acks\":\"8\"}]\t");  

    List<String> llist = new LinkedList<String>();
    while (m.find()) {    
        llist.add(m.group(1));
    }    
    if(llist.size() == 0) {    
        System.out.println("No match found.");    
    } else {
        System.out.println("Output : " + llist.toString());
    }
   }
}

Upvotes: 1

markalex
markalex

Reputation: 13432

It is unclear precisely what you are trying to do.

If all you want is to leave out [,],, and digits, you can replace everything else with empty string using the following regex: [^\d,[\]]+

And if you only need to extract digits from objects with single field "acks", you could replace \{"acks":"(\d+)"\} with $1.
Demo here.

Upvotes: 0

Related Questions