【问题标题】:Capture substring within delimiters and excluding characters using regex使用正则表达式捕获分隔符内的子字符串并排除字符
【发布时间】:2018-11-01 10:47:29
【问题描述】:

正则表达式模式如何看起来像捕获 2 个定界符之间的子字符串,但不包括第一个定界符之后和最后一个定界符(如果有)之前的某些字符(如果有)? 例如,输入字符串如下所示:

var input = @"Not relevant {

#AddInfoStart Comment:String:=""This is a comment"";

AdditionalInfo:String:=""This is some additional info"" ;

# } also not relevant";

捕获应包含“{”和“}”之间的子字符串,但不包括在开始分隔符“{”之后的任何空格、换行符和“#AddInfoStart”字符串(只要它们存在),并且不包括任何空格, 换行符和 ";"和结束分隔符“}”之前的“#”字符(如果它们中的任何一个存在)。

捕获的字符串应该是这样的

Comment:String:=""This is a comment"";

AdditionalInfo:String:=""This is some additional info""

“:”和“:=”内部分隔符之前或之后可能有空格,并且“:=”之后的值并不总是标记为字符串,例如:

{  Val1 : Real := 1.7  }

对于数组,使用以下语法:

arr1 : ARRAY [1..5] OF INT := [2,5,44,555,11];
arr2 : ARRAY [1..3] OF REAL

【问题讨论】:

  • 我看过你的编辑。是否所有数字都有. 作为小数分隔符?数字后面有空格吗?请编辑您的初始字符串并添加更多示例
  • 字符串、实数等类型呢?有固定的类型列表吗?
  • 基本上是整数、浮点数、字符串和布尔数据类型以及它们的数组,如此处所述link

标签: c# .net regex substring capture


【解决方案1】:

这是我的解决方案:

  1. 删除括号外的内容
  2. 使用正则表达式获取括号内的值

代码:

var input = @"Not relevant {

#AddInfoStart Comment:String:=""This is a comment"";

            Val1 : Real := 1.7

AdditionalInfo:String:=""This is some additional info"" ;

# } also not relevant";

// remove content outside brackets
input = Regex.Replace(input, @".*\{", string.Empty);
input = Regex.Replace(input, @"\}.*", string.Empty);

string property = @"(\w+)"; 
string separator = @"\s*:\s*"; // ":" with or without whitespace
string type = @"(\w+)"; 
string equals = @"\s*:=\s*"; // ":=" with or without whitespace
string text = @"""?(.*?)"""; // value between ""
string number = @"(\d+(\.\d+)?)"; // number like 123 or with a . separator such as 1.45
string value = $"({text}|{number})"; // value can be a string or number
string pattern = $"{property}{separator}{type}{equals}{value}";

var result = Regex.Matches(input, pattern)
                  .Cast<Match>()
                  .Select(match => new
                  {
                      FullMatch = match.Groups[0].Value, // full match is always the 1st group
                      Property = match.Groups[1].Value, 
                      Type = match.Groups[2].Value, 
                      Value = match.Groups[3].Value 
                  })
                  .ToList();

【讨论】:

  • 谢谢,我正在努力理解您的代码。为什么分隔符“{”和“}”不必出现在正则表达式模式中?
  • @RickyTad 我的错误,我忘了你想要括号内的匹配项。我已经编辑了我的代码,看看。之前进行一些清理比尝试使用单个正则表达式要容易得多。
  • 是否可以从输入字符串中捕获 {} 括号外的所有内容,即使输入字符串中存在多个分隔符 {} 括号对?
  • @RickyTad 是的,这是可能的,但请记住,我的代码假设只有一对 {}
  • 该模式在解析“Val1 : Real := 1.7”之类的内容时看起来如何?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多