2

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"
5
  • You can implode your string based on , Commented Apr 6, 2016 at 10:32
  • Problem is that there are commas within the values, it makes the logic so much more difficult, because what's the condition for when to split on comma and when shouldn't you split on comma? You likely need to introduce some escape based logic Commented Apr 6, 2016 at 10:33
  • @Shafizadeh Won't that split up the RGB and Style directives? Commented Apr 6, 2016 at 10:33
  • @AllanS.Hansen Yes, that's the problem. Commented Apr 6, 2016 at 10:34
  • (\w+)\s+->\s+({[^{}]*}|(?:.*?)(?=, \w+\s+->|$)). Commented Apr 6, 2016 at 10:43

2 Answers 2

3

You can use the following to split:

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

See DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, looks promising... except it split the Style directive. Think I need to add something for the curly braces.
Yeah.. it will be difficult to consider where to split with that.. it might need changing the string with escape characters
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.