[英]A More Efficient Way to Parse a String in C#
I have this code that reads a file and creates Regex groups. 我有这段代码可读取文件并创建Regex组。 Then I walk through the groups and use other matches on keywords to extract what I need.
然后,我遍历各个组,并在关键字上使用其他匹配项来提取所需的内容。 I need the stuff between each keyword and the next space or newline.
我需要每个关键字和下一个空格或换行符之间的内容。 I am wondering if there is a way using the Regex keyword match itself to discard what I don't want (the keyword).
我想知道是否有一种方法可以使用Regex关键字匹配本身来丢弃我不需要的内容(关键字)。
//create the pattern for the regex
String VSANMatchString = @"vsan\s(?<number>\d+)[:\s](?<info>.+)\n(\s+name:(?<name>.+)\s+state:(?<state>.+)\s+\n\s+interoperability mode:(?<mode>.+)\s\n\s+loadbalancing:(?<loadbal>.+)\s\n\s+operational state:(?<opstate>.+)\s\n)?";
//set up the patch
MatchCollection VSANInfoList = Regex.Matches(block, VSANMatchString);
// set up the keyword matches
Regex VSANNum = new Regex(@" \d* ");
Regex VSANName = new Regex(@"name:\S*");
Regex VSANState = new Regex(@"operational state\S*");
//now we can extract what we need since we know all the VSAN info will be matched to the correct VSAN
//match each keyword (name, state, etc), then split and extract the value
foreach (Match m in VSANInfoList)
{
string num=String.Empty;
string name=String.Empty;
string state=String.Empty;
string s = m.ToString();
if (VSANNum.IsMatch(s)) { num=VSANNum.Match(s).ToString().Trim(); }
if (VSANName.IsMatch(s))
{
string totrim = VSANName.Match(s).ToString().Trim();
string[] strsplit = Regex.Split (totrim, "name:");
name=strsplit[1].Trim();
}
if (VSANState.IsMatch(s))
{
string totrim = VSANState.Match(s).ToString().Trim();
string[] strsplit=Regex.Split (totrim, "state:");
state=strsplit[1].Trim();
}
It looks like your single regex should be able to gather all you need. 看起来您的单个正则表达式应该可以收集您需要的所有内容。 Try this:
尝试这个:
string name = m.Groups["name"].Value; // Or was it m.Captures["name"].Value?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.