William
William

Reputation: 79

Regex capture set of groups that might or might not exist

I have a bit of problem working with regex grouping. Lets say i have the following string :

"Test, some information, more stuff (addtional information)"

I want to split this into 4 groups as the following:

group1: Test
group2: some information
group3: more stuff
group4: additional information

However group 2 may or may not exist and the same with group 4.

example:
"Test, more stuff" (group 2 and 4 don't exist)
"Test, some informattion, more stuff" (group 4 don't exist)
"test, more stuff (additional information)" (group 2 dont exist)

What I'ved started:

(.*?),(.*?),(.*?)\\((.*?)\\)

How can I proceed from here?

Upvotes: 4

Views: 449

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

I suggest you to use string.split.

String s = "Test, some information, more stuff (addtional information)";
String parts[] = s.split(",\\s+|\\s*[()]");
System.out.println(Arrays.toString(parts));

Output:

[Test, some information, more stuff, addtional information]

\s+ matches one or more spaces.

OR

You could split your input according to "\\s*[,()]\\s*" regex suggested by our mod.

OR

make the 2 and 4 group as optional.

"^(.*?)(?:,(.*?))?,([^()\\n]*)(?: \\((.*?)\\))?$"

DEMO

Upvotes: 2

Related Questions