简体   繁体   中英

Get substring from string with a regex

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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