【问题标题】:Is there a way to use Regex to split I[1,2]?有没有办法使用正则表达式来拆分 I[1,2]?
【发布时间】:2021-03-23 13:44:33
【问题描述】:

我正在从 C# 中的 XML 文件中提取一个字符串,并且需要 "I[1,2]" 中的第二个数字,即 2

  Regex regex = new Regex(@"\[.*?\]");
  MatchCollection matches = regex.Matches(inputChannel.Value);

  var result = matches[0].Value.Split().Where(x => x.StartsWith("[") && x.EndsWith("]"))
                 .Select(x => x.Replace("[", string.Empty).Replace("]", string.Empty))
                 .ToList();

在哪里inputChannel.value = "I[1;2]"

此代码获取两个数字并将它们粘贴到一个列表中,但是有没有办法将两个数字拆分并放入一个列表中?

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    您可以使用捕获组来获取第二个数字,而不是使用拆分。

    I\[[0-9]+;([0-9]+)]
    
    • I\[匹配I[
    • [0-9]+; 匹配 1+ 个数字 0-9 和 ;
    • ([0-9]+)捕获组1,匹配1+位0-9
    • ] 匹配 ] 字符

    查看regex demo

    string pattern = @"I\[[0-9]+;([0-9]+)]";
    string input = @"I[1;2]";        
    Match m = Regex.Match(input, pattern); 
    Console.WriteLine(m.Groups[1].Value); // 2
    

    或使用环视:

    (?<=I\[[0-9]+;)[0-9]+(?=])
    
    • (?&lt;=I\[[0-9]+;) 正向后视,断言I[,1+ 数字后跟; 向左
    • [0-9]+ 匹配 1+ 位 0-9
    • (?=]) 正向前瞻,向右断言 ]

    查看另一个regex demo

    string pattern = @"(?<=I\[[0-9]+;)[0-9]+(?=])";
    string input = @"I[1;2]";        
    Match m = Regex.Match(input, pattern); 
    Console.WriteLine(m.Value); // 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多