Get substring from string with regular expression

How can I get four numbers from strings in this format:

Some texts with number 1 ( 10 / 100 ), some other texts ... From -10 ° C to 50 ° C

Some other texts with two rooms ( 10 / 100 ), some other texts ... From -11 ° C to -2 ° C

Some other texts from -30 numbers ( 100 / 1001 ) some other texts ... from 2 ° C to 12 ° C

The first two numbers are in brackets and are separated by a slash. In addition, there is no space behind the slash; I had to add it in order to be able to make the numbers bold. Both numbers are positive integers.

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

The fourth number is always “° C to” and the last “° C”.

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

I am using C # and .NET 3.5.

+3
source share
1 answer

This will work:

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

4 ( , ) - , "", "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);
+3

Source: https://habr.com/ru/post/1759756/


All Articles