Home > front end >  C# Distinguish between first and second match
C# Distinguish between first and second match

Time:12-02

I am using regex to extract the numbers from a string which contains a range. The range could be "less than x", "greater than x" or "between x and y":

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

Below is the relevant code snippet. In the case of "less than x" and "greater than x" I use the RegEx (\d*,\d*)?(\d*) to capture the integer/decimal.

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,

In the case of "between x and y" I am having difficulties in constructing a RegEx which would extract the relevant number. Is there a way to do this using RegEx?

CodePudding user response:

You can use

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

See the regex demo. Details:

  • (\d (?:,\d )?) - Capturing group 1: one or more digits followed with an optional occurrence of a comma and one or more digits
  • \s*-\s* - a - enclosed with zero or more whitespace chars
  • (\d (?:,\d )*) - Capturing group 2: one or more digits followed with an optional occurrence of a comma and one or more digits

Now, match contains a 3,50000 - 11,0 substring in Group 0, and the rest two groups contain your values:

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

See the C# demo:

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

CodePudding user response:

try this expression :

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