Get substring from string with a regex

10,271

This will work:

^.*\( *(\d+) */ *(\d+) *\)\D*?From +(-?\d+)°C +to +(-?\d+)°C$

It just reads 4 numbers (first two always positive and the second two positive or negative) in a text strings - it looks for parentheses for the first two numbers and does check where the last two numbers is with regards to "From" and "to"

var pattern = @"^.*\( *(\d+) */ *(\d+) *\)\D*?From +(-?\d+)°C +to +(-?\d+)°C$";

var result = Regex.Match("Some other text with 2 numbers (10/ 100) some other text... From -11°C to -2°C", pattern);

var num1 = int.Parse(result.Groups[1].Value);
var num2 = int.Parse(result.Groups[2].Value);
var num3 = int.Parse(result.Groups[3].Value);
var num4 = int.Parse(result.Groups[4].Value);
Share:
10,271
sventevit
Author by

sventevit

Updated on July 11, 2022

Comments

  • sventevit
    sventevit almost 2 years

    How can I get my four numbers from strings with this format:

    Some text with 1 numbers (10/ 100) some other text... From -10°C to 50°C

    Some other text with 2 numbers (10/ 100) some other text... From -11°C to -2°C

    Some other text with -30 numbers(100/ 1001) some other text... From 2°C to 12°C

    First two numbers are in the brackets and seperated with a slash. Also, there is no space behind the slash, I had to add it in order to be able to make numbers bold. Both numbers are positive integers.

    Third number is always between the "From " and first "°C".

    Fourth number is always behind the "°C to " and last "°C".

    There are no other brackets in the string and there is only one "From " word in it.

    I am using C# and .NET 3.5.