-3

如何将字符串转换为组

细绳:

TableStart:Name="valueName";ClassName="valueClassName";MasterDatasource="valueMasterDatasource";Condition="valueCondition";ConditionParams="valueConditionParams";OrderBy="valueOrderBy"

输出组:

Name = "valueName"
ClassName = "valueClassName"
MasterDatasource = "valueMasterDatasource"
Condition = "valueCondition"
ConditionParams = "valueConditionParams"
OrderBy = "valueOrderBy"

正则表达式?

TableStart:Name=(?<Name>".*");ClassName=(?<ClassName>".*");MasterDatasource=(?<MasterDatasource>".*");Condition=(?<Condition>".*");ConditionParams=(?<ConditionParams>".*");OrderBy=(?<OrderBy>".*")
4

2 回答 2

1

尝试使用此代码段:

var s = "TableStart:Name=\"valueName\";ClassName=\"valueClassName\";MasterDatasource=\"valueMas" +
"terDatasource\";Condition=\"valueCondition\";ConditionParams=\"valueConditionParams\"" +
";OrderBy=\"valueOrderBy\"";

var reg = new Regex("TableStart:Name=(?<Name>\".*\");ClassName=(?<ClassName>\".*\");MasterDatasource=(?<Ma" +
"sterDatasource>\".*\");Condition=(?<Condition>\".*\");ConditionParams=(?<ConditionPa" +
"rams>\".*\");OrderBy=(?<OrderBy>\".*\")");

Match match = reg.Match(s);
GroupCollection groups = match.Groups;
for (int i = 1; i < groups.Count; i++)
{
    Console.WriteLine("{0} = {1}", reg.GroupNameFromNumber(i), groups[i].Value);
}

印刷:

Name = "valueName"
ClassName = "valueClassName"
MasterDatasource = "valueMasterDatasource"
Condition = "valueCondition"
ConditionParams = "valueConditionParams"
OrderBy = "valueOrderBy"

编辑:或者您可以使用更简洁和更短的正则表达式

var reg = new Regex("\\w+\\=\"\\w+\"");

foreach (Match match in reg.Matches(s))
{
    var values = match.Value.Split('=');
    Console.WriteLine ("{0} = {1}",values[0], values[1]);
}

打印相同。

于 2013-01-08T07:38:29.373 回答
0

无正则表达式的替代方案:

string input = "TableStart:Name=\"valueName\";ClassName=\"valueClassName\";MasterDatasource=\"valueMasterDatasource\";Condition=\"valueCondition\";ConditionParams=\"valueConditionParams\";OrderBy=\"valueOrderBy\"";
input = input.Replace("TableStart:", "");
string[] nameValues = input.Split(';');
foreach (string nameValue in nameValues){
    string[] couple = nameValue.Split('=');
    string name = couple[0];
    string value = couple[1].Trim('"');
    Console.WriteLine("{0} = {1}", name, value);
}
于 2013-01-08T07:38:43.953 回答