0

这是我当前字符串的样子:

Data={Person, Id, Destination={Country, Price}}

它也可能看起来像这样

Data={Person, Id, Specification={Id, Destination={Country, Price}}}

我需要的是一种搜索整个字符串并能够获得的方法:

搜索,然后获取第一个和最后一个括号之间的Data整个数据 Data={**GET THIS**}

然后用获得的数据我应该能够得到:

Person, Id,然后如果我发现Specification对数据执行相同操作,则将内容放入到最后一个括号,然后对 . 执行相同操作Destination

任何线索我该怎么办?我为此使用 C#。

4

2 回答 2

1

检索大括号之间所有内容的函数:

public string retrieve(string input)
{
    var pattern = @"\{.*\}";
    var regex = new Regex(pattern);
    var match = regex.Match(input);
    var content = string.Empty;
    if (match.Success)
    {
        // remove start and end curly brace
        content = match.Value.Substring(1, match.Value.Length - 2);
    }
    return content;
}

然后使用函数检索内容:

var input = @"Data={Person, Id, Specification={Id, Destination={Country, Price}}}";
var content = retrieve(input);
Console.Out.WriteLine(content);
if (!string.IsNullOrEmpty(content))
{
    var subcontent = retrieve(content);
    Console.Out.WriteLine(subcontent);
    // and so on...
}

输出是:

Person, Id, Specification={Id, Destination={Country, Price}}
Id, Destination={Country, Price}

您不能使用string.Split(',')来检索PersonId,因为它还会在括号之间拆分字符串,而您不希望这样。而是从正确的位置使用建议的string.IndexOf两次,您将正确获得子字符串:

// TODO error handling
public Dictionary<string, string> getValues(string input)
{
    // take everything until =, so string.Split(',') can be used
    var line = input.Substring(0, input.IndexOf('='));
    var tokens = line.Split(',');
    return new Dictionary<string, string> { { "Person" , tokens[0].Trim() }, { "Id", tokens[1].Trim() } };
}

该函数应该用于检索到的内容:

var input = @"Data={Person, Id, Specification={Id, Destination={Country, Price}}}";
var content = retrieve(input);
var tokens = getValues(content);
Console.Out.WriteLine(string.Format("{0} // {1} // {2}", content, tokens["Person"], tokens["Id"]));
if (!string.IsNullOrEmpty(content))
{
    var subcontent = retrieve(content);
    Console.Out.WriteLine(subcontent);
    var subtokens = getValues(subcontent);
    Console.Out.WriteLine(string.Format("{0} // {1} // {2}", subcontent, subtokens["Person"], subtokens["Id"]));
}

输出是:

Person, Id, Specification={Id, Destination={Country, Price}} // Person // Id
Id, Destination={Country, Price}
Id, Destination={Country, Price} // Id // Destination
于 2013-10-12T08:30:45.653 回答
0

你可以试试这样的 -

string str = "Data={Person, Id, Specification={Id, Destination={Country, Price}}}";
string[] arr = str.Split(new char[]{'{','}','=',','},StringSplitOptions.RemoveEmptyEntries).Where(x => x.Trim().Length != 0).Select(x => x.Trim()).ToArray();
foreach(string s in arr)
    Console.WriteLine(s);

Where(x => x.Trim().Length != 0)part 用于删除仅包含空格的字符串。

Select(x => x.Trim())part 用于删除所有子字符串的前导和尾随空格。

结果是

Data
Person
Id
Specification
Id
Destination
Country
Price

所以现在您可以遍历数组并解析数据。基本逻辑是

if(arr[i] == "Data") 那么接下来的两项将是 person 和 id

if(arr[i] == "Destination") 那么接下来的两项将是 id 和 destination

if(arr[i] == "specification") 那么接下来的两项是国家和价格

于 2013-10-12T17:43:10.990 回答