c# - 复杂的字符串拆分

标签 c# regex string parsing split

我有一个类似下面的字符串:

[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:.*)

Working demo

此正则表达式背后的想法是在组 123 中捕获您想要的内容。

您可以通过这张图轻松地看到它:

Regular expression visualization

比赛信息

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:.*)

Regular expression visualization

Working demo

或者甚至至少强制一个字符:

(\[.+?])\|(.+)\|(Description:.+)

Regular expression visualization

关于c# - 复杂的字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633258/

相关文章:

C# 线程安全快速(估计)计数器

asp.net - 图像的正则表达式?

c# - 用双反斜杠替换单反斜杠

java - 如何转义Java正则表达式中的字符

java - 附加字符串时出现速度问题

java - java中有什么方法可以判断一个字符串是否包含HTML标签

c - 关于C中字符串数组的qsort

c# - 使用 SQL 更新 250k 行的更快方法

C# Windows 10现代系统托盘菜单

c# - 具有多个 TextBlock 的 XAML 样式按钮