【发布时间】:2014-02-26 10:41:40
【问题描述】:
我尝试解析这样的字符串:
"#1#Process#{some process|info}{some name|some info {child info|child info}}{some name|some info}"
在几条消息中创建这样的字符串:
#1#Process#
-some process|info
-some name|some info
-child info|child info
-some name|some info
我正在尝试使用 RegExp 和以下代码:
using System;
using System.Collections;
using System.Text.RegularExpressions;
namespace prRegEXP
{
class Program
{
static String st="";
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
var pattern = @"\{(.*?)\}";
var query = "#1#Process#{some process|info}{some name|some info {child info|child info}}{some name|some info}";
FindTree (pattern, query);
Console.WriteLine(st);
Console.WriteLine();
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
private static void FindTree (String pattern, String query) {
var matches = Regex.Matches(query, pattern);
foreach (Match m in matches) {
st += m.Groups[1] + "\n";
if (Regex.IsMatch(m.Groups[1].ToString(), @"\{(.*?)" )) {
FindTree (@"\{(.*?)", m.Groups[1].ToString());
}
}
}
}
}
它基于我发现的example solution,我想创建一些消息树来处理内部消息(如child info|child name)。而且可能有很多。
我不知道如何匹配子表达式并将其以递归参数发送。有什么想法或解决方法吗?
【问题讨论】:
-
+1 表示查询字符串!
-
您可以通过使用递归正则表达式来实现这一点,但它需要很好的理解才能有效地工作(即使语言支持 - 递归捕获组的检索可能会很棘手)。没有它 - 你可以为你的 2-depth 示例构建一个 2-depth 模式,但是用 depth-counter 编写一个适当的标记器会容易得多......