使用正则表达式拆分嵌套参数

时间:2016-04-06 10:31:19

标签: c# regex parsing split

任何人都可以帮助使用正则表达式方法(或其他)来拆分此字符串

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

获取

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

包含以下五个字符串?

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

2 个答案:

答案 0 :(得分:3)

您可以使用以下内容进行拆分:

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

请参阅DEMO

答案 1 :(得分:2)

试试这个

选项1:

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

Regex Demo

输入:

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

输出:

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`

说明:

([^,]+{[^}]+})捕获Any -> {Any}
([^,]+\[[^\]]+\])抓取Any -> [Any]
([^,]+)会抓取除,

以外的其他人

选项2:

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

Regex Demo

输出:

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