-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 に答える