我有一个字符串
event FILE[2]::OnProc {;? Msg("Step2") } event FILE[test]::OnProc {;? Msg("Step3.1.1") }
我想分成几部分。所需的输出将列为
列表List
[0]
2
;? Msg("Step2")
[1]
test
;? Msg("Step3.1.1")
如您所见,[]
之间的字符串是列表中第i个条目的第一个条目,{}
之间的字符串是下一个条目。
请问您的帮助我如何获得所需的清单?
更新
我已经尝试过这段代码,但它不会是正确的。
Regex regex = new Regex(@"event FILE\[(?<type>[^\]]*)\]::OnProc? ?{;(?<msg>[^}]*)}");
答案 0 :(得分:1)
您可以使用Split.Extract(没有正则表达式的方法):
var list = new List<KeyValuePair<string, string>>();
string str = "event FILE[2]::OnProc {;? Msg(\"Step2\") } event FILE[test]::OnProc {;? Msg(\"Step3.1.1\") }";
List<string> events = Split.Extract(str, "event", "event");
foreach (string e in events)
{
list.Add(new KeyValuePair<string, string>(
Split.Extract(e, "FILE[", "]").First(),
Split.Extract(e, "{", "}").First()
));
}
额外的Split
班级:
public class Split
{
public static List<string> Extract(string source, string splitStart, string splitEnd)
{
try
{
var results = new List<string>();
string[] start = new string[] { splitStart };
string[] end = new string[] { splitEnd };
string[] temp = source.Split(start, StringSplitOptions.None);
for (int i = 1; i < temp.Length; i++)
{
results.Add(temp[i].Split(end, StringSplitOptions.None)[0]);
}
return results;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
(我不喜欢复杂的正则表达式:P)
答案 1 :(得分:0)
string toSplit = "event FILE[2]::OnProc {;? Msg("Step2") } event FILE[test]::OnProc {;? Msg("Step3.1.1") }";
string [] splitString = toSplit.split(new string [] {"event FILE"}, String.SplitOptions.None);
List<string> parts = new List();
foreach(string s in splitString )
{
parts.Add({reg ex for []); //psuedocoded because I don't like to figure out regex
parts.Add({reg ex for {}); //psuedocoded because I don't like to figure out regex
}
我相信其他人可以填写爱他们的RegEx!
答案 2 :(得分:0)
感谢所有答案。我认为我在这里取决于Regex将是一个很好的。
Regex regex = new Regex(@"event ACTION\[(?<type>[^\]]*)\]::OnProc {? ?;(?<msg>[^}]*)}");
List<ScriptData> Script = new List<ScriptData>();
string ScriptTxt1 = List.ScriptComp[0].CompScrTxt;
//convert first script
foreach (Match match in regex.Matches(ScriptTxt1))
{
Script.Add(new ScriptData(match.Groups["type"].Value, match.Groups["msg"].Value));
}
public class ScriptData
{
public string Type { get; private set; }
public string ScriptMessage { get; private set; }
public ActionScriptData(string type, string msg)
{
Type = type;
ScriptMessage = msg;
}
public ScriptData()
{
Type = null;
ScriptMessage = null;
}
}