正则表达式使用不同的分隔符进行分割

时间:2017-04-20 10:03:52

标签: c# regex

我想分割一个具有以下模式的文本行:

 Name : Type := start_value ; // comment

start_valuecomment是可选的,分号是必需的。这是几行的例子:

 MinF : DINT ;  //Minimum frequentie: 0 = 0,0 Hz
 MaxF : DINT  := L#100000;  //Maximum reference:75000 = 75,0Hz
 RampUp : DINT  := L#50;    //Ramp up tijd: 100 = 1,00 seconde
 RampDown : DINT  := L#50;  //Ramp down tijd: 100 = 1,00 seconde
 V1 : DINT ;    //Snelheid 1:  50,00%

我可以只使用一个正则表达式吗?

1 个答案:

答案 0 :(得分:1)

我建议匹配而不是拆分。借助pattern喜欢

string pattern = 
  @"^\s*(?<Name>[A-Za-z0-9]+)\s*:\s*(?<Type>[A-Za-z0-9]+)(\s*:=\s*(?<Value>\S*))?\s*;\s*(//(?<Comment>.*))?$";            

我们可以轻松解析这些行

string[] source = new string[] {
  "MinF : DINT ;  //Minimum frequentie: 0 = 0,0 Hz",
  "MaxF : DINT  := L#100000;  //Maximum reference:75000 = 75,0Hz",
  "RampUp : DINT  := L#50;    //Ramp up tijd: 100 = 1,00 seconde",
  "RampDown : DINT  := L#50;  //Ramp down tijd: 100 = 1,00 seconde",
  "V1 : DINT ;    //Snelheid 1:  50,00%",
};

var result = source
  .Select(line => Regex.Match(line, pattern))
  .Where(match => match.Success)
  .Select(match => new {
     name = match.Groups["Name"].Value,
     type = match.Groups["Type"].Value,
     value = match.Groups["Value"].Value,
     comment = match.Groups["Comment"].Value, })
  .ToArray();

测试

Console.Write(string.Join(Environment.NewLine, result
  .Select(item => $"{item.name,-8} {item.type,4} {item.value,-8} {item.comment}")));

结果:

MinF     DINT          Minimum frequentie: 0 = 0,0 Hz
MaxF     DINT L#100000 Maximum reference:75000 = 75,0Hz
RampUp   DINT L#50     Ramp up tijd: 100 = 1,00 seconde
RampDown DINT L#50     Ramp down tijd: 100 = 1,00 seconde
V1       DINT          Snelheid 1:  50,00%