我有一个类似下面的字符串:
[Testing.User]|Info:([Testing.Info]|Name:([System.String]|Matt)|Age:([System.Int32]|21))|Description:([System.String]|This is some description)
你可以把它看成这棵树:
- [Testing.User]
- Info
- [Testing.Info]
- Name
- [System.String]
- Matt
- Age
- [System.Int32]
- 21
- Description
- [System.String]
- This is some description
如您所见,它是类 Testing.User
的字符串序列化/表示形式
我希望能够进行拆分并在结果数组中获取以下元素:
[0] = [Testing.User]
[1] = Info:([Testing.Info]|Name:([System.String]|Matt)|Age:([System.Int32]|21))
[2] = Description:([System.String]|This is some description)
我不能按 |
拆分,因为那样会导致:
[0] = [Testing.User]
[1] = Info:([Testing.Info]
[2] = Name:([System.String]
[3] = Matt)
[4] = Age:([System.Int32]
[5] = 21))
[6] = Description:([System.String]
[7] = This is some description)
如何获得预期结果?
我不太擅长正则表达式,但我知道这是一种非常可能的解决方案。
最佳答案
使用正则表达式前瞻
您可以像这样使用正则表达式:
(\[.*?])|(\w+:.*?)\|(?=Description:)|(Description:.*)
此正则表达式背后的想法是在组 1
、2
和 3
中捕获您想要的内容。
您可以通过这张图轻松地看到它:
比赛信息
MATCH 1
1. [0-14] `[Testing.User]`
MATCH 2
2. [15-88] `Info:([Testing.Info]|Name:([System.String]|Matt)|Age:([System.Int32]|21))`
MATCH 3
3. [89-143] `Description:([System.String]|This is some description)`
正则表达式
另一方面,如果你不喜欢上面的正则表达式,你可以像这样使用另一个:
(\[.*?])\|(.*)\|(Description:.*)
或者甚至至少强制一个字符:
(\[.+?])\|(.+)\|(Description:.+)
关于c# - 复杂的字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633258/