繁体   English   中英

C# 区分第一匹配和第二匹配

[英]C# Distinguish between first and second match

我正在使用正则表达式从包含范围的字符串中提取数字。 范围可以是"less than x""greater than x""between x and y"

"10 - 22"
"< 0,5"
"3,50000 - 11,0"
"< 120000"  
"> 12"

下面是相关的代码片段。 "less than x""greater than x"的情况下,我使用 RegEx (\d*,\d*)?(\d*)来捕获整数/小数。

Low = r.Descr.Contains('>') 
    ? new Quantity {
        Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value)
    } 
    : r.Descr.Contains('-') 
    ? new Quantity {
        Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value) 
    } 
    : null,
High = r.Descr.Contains('<') 
    ? new Quantity {
        Value = Convert.ToDecimal(Regex.Match(r.Descr, @"(\d*,\d*)?(\d*)").Value) 
    }
    : r.Descr.Contains('-') 
    ? new Quantity { 
        Value = Convert.ToDecimal(Regex.Match(r.Descr, @"").Value) 
    } 
    : null,

"between x and y"的情况下,我在构建一个提取相关数字的 RegEx 时遇到了困难。 有没有办法使用正则表达式来做到这一点?

试试这个表达式:

(\d+,?\d+\s*-\s*\d+,?\d+)|(<\s*\d+,?\d+)|(>\s*\d+,?\d+)

您可以使用

var match = Regex.Match(text, @"(\d+(?:,\d+)?)\s*-\s*(\d+(?:,\d+)*)");

请参阅正则表达式演示 详情

  • (\d+(?:,\d+)?) - 捕获组 1:一位或多位数字后跟可选的逗号和一位或多位数字
  • \s*-\s* - a -用零个或多个空格字符括起来
  • (\d+(?:,\d+)*) - 捕获组 2:一位或多位数字后跟可选的逗号和一位或多位数字

现在, match在第 0 组中包含3,50000 - 11,0 11,0 substring,并且 rest 两组包含您的值:

if (match.Success)
{
    Console.WriteLine("{0} - first number", match.Groups[1].Value);
    Console.WriteLine("{0} - second number", match.Groups[2].Value);
}

请参阅C# 演示

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
 
public class Test
{
    public static void Main()
    {
        var text = "some words....3,50000 - 11,0 .... text....";
        var match = Regex.Match(text, @"(\d+(?:,\d+)?)\s*-\s*(\d+(?:,\d+)*)");
 
        if (match.Success)
        {
            Console.WriteLine("{0} - first number", match.Groups[1].Value);
            Console.WriteLine("{0} - second number", match.Groups[2].Value);
        }
    }
}

Output:

3,50000 - first number
11,0 - second number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM