Question: I am currently writing a java program with regular expression but I am struggling as I am pretty new in regex.

```
KEY_EXPRESSION = "[a-zA-z0-9]+";
VALUE_EXPRESSION = "[a-zA-Z0-9\\*\\+,%_\\-!@#\\$\\^=<>\\.\\?';:\\|~`&\\{\\}\\[\\]/ ]*";
CHUNK_EXPRESSION = "(" + KEY_EXPRESSION + ")\\((" + VALUE_EXPRESSION + ")\\)";

```

The target syntax is `key(value)+key(value)+key(value)`. Key is alphanumeric and value is allowed to be any combination.

This has been okay so far. However, I have a problem with `'('`, `')'` in value. If I place `'('` or `')'` in the value, value includes all the rest.

e.g. `number(abc(kk)123)+status(open)` returns `key:number`, `value:abc(kk)123)+status(open`  

It is supposed to be two pairs of key-value.

Can you guys suggest to improve the expression above?

Answer: 
Get the matched group from index 1 and 2

```
([a-zA-Z0-9]+)\((.*?)\)(?=\+|$)

```

Here is [online demo](http://regex101.com/r/vG0nE6/8)

The above regex pattern looks of for `)+` as delimiter between keys and values.

**Note:** The above regex pattern will not work if value contains `)+` for example `number(abc(kk)+123+4+4)+status(open)`

![enter image description here](https://i.stack.imgur.com/drOXR.png)

Sample code:

```
String str = "number(abc(kk)123)+status(open)";
Pattern p = Pattern.compile("([a-zA-Z0-9]+)\\((.*?)\\)(?=\\+|$)");
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.println(m.group(1) + ":" + m.group(2));
}

```

output:

```
number:abc(kk)123
status:open

```
I'll do a little assumption that you're able to add a + at the end of your chunk 
i.e. `number(abc(kk)123)+status(open)+`

If it is possible you'll have it work with:

```
KEY_EXPRESSION = "[a-zA-z0-9]+";
VALUE_EXPRESSION = "[a-zA-Z0-9\\*\\+,%_\\-!@#\\$\\^=<>\\.\\?';:\\|~`&\\{\\}\\[\\]\\(\\)/ ]*?";
CHUNK_EXPRESSION = "(" + KEY_EXPRESSION + ")\\((" + VALUE_EXPRESSION + ")\\)+";

```

The changes are on line 2 adding the `(` `)` with escaping and replacing `*` by `*?`

The `?` turn off the greedy matching and try to keep the shortest match (reluctant operator).

On line 3 adding a `+` at the end of the mask to help separate the `key(value)` fields.