我们可以使用以下正则表达式轻松提取值:
(\w+) -- (\w+)\[label="(\w+)",weight="([0-9]*\.?[0-9]+)"\];
完整代码:
string rawData = File.ReadAllText("H:\\data.txt");
string pattern = "(\\w+) -- (\\w+)\\[label=\"(\\w+)\",weight=\"([0-9]*\\.?[0-9]+)\"\\];";
var matches = Regex.Matches(rawData,pattern);
编辑:
这是我们从每个匹配对象中获取不同值的方法
定义一个Edge
类,仅用于保存数据
class Edge {
public string NodeALabel;
public string NodeBLabel;
public double Weight;
public string EdgeLabel;
}
从每个匹配项中获取组值。组号由组左侧的左括号括起来决定。
var edgeList = matches.Select(match => new Edge() {
NodeALabel= match.Groups[1].Value,NodeBLabel= match.Groups[2].Value,Weight= double.Parse(match.Groups[4].Value),EdgeLabel= match.Groups[3].Value
}).ToList();
本文链接:https://www.f2er.com/3019441.html