c# - Split nested parameters using regex


Keywords:c# 


Question: 

Can anyone help with a regex method (or other) to split this string

string text = "Item -> \"Elephant\", Branches -> 10, Color -> RGB[1, 0, 1], Style -> {Font -> \"Courier New\", Size -> 7}, Display -> True";

to obtain

List<string> directives = new List<string>();

containing the following five strings?

"Item -> \"Elephant\""
"Branches -> 10"
"Color -> RGB[1, 0, 1]"
"Style -> {Font -> \"Courier New\", Size -> 7}"
"Display -> True"

2 Answers: 

Try this

Option 1:

([^,]+{[^}]+})|([^,]+\[[^\]]+\])|([^,]+)

Regex Demo

Input:

Item -> \"Elephant\", Branches -> 10, Color -> RGB[1, 0, 1], Style -> {Font -> \"Courier New\", Size -> 7}, Display -> True

Output:

MATCH 1
3.  [0-20]  `Item -> \"Elephant\"`
MATCH 2
3.  [21-36] ` Branches -> 10`
MATCH 3
2.  [37-59] ` Color -> RGB[1, 0, 1]`
MATCH 4
1.  [60-106]    ` Style -> {Font -> \"Courier New\", Size -> 7}`
MATCH 5
3.  [107-123]   ` Display -> True`

Explanation:

([^,]+{[^}]+}) captures Any -> {Any}
([^,]+\[[^\]]+\]) captures Any -> [Any]
([^,]+) captures others except ,

Option 2:

,\s*(?![^{]+}|[^\[]+\])

Regex Demo

Output:

Item -> \"Elephant\"
Branches -> 10
Color -> RGB[1, 0, 1]
Style -> {Font -> \"Courier New\", Size -> 7}
Display -> True
 

You can use the following to split:

,\s*(?=\s*[^,]+-)

See DEMO