tags:

views:

70

answers:

1

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.

+3  A: 

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);
lasseespeholt
First two numbers are alwas positive, and the second two numbers could be negative or positive. I can use your solution, because there are only these four numbers in the strings :)
_simon_
Okay cool, I can make it more strict with regards to parentheses etc.
lasseespeholt
My fault, I can also have numbers before the first brackets, so this isn't exactly the right solution... Edited first post.
_simon_
Okay, I have edited the post now (all of it) it works with your examples.
lasseespeholt
I have changed it again. It worked fine before, but I have made so more than one whitespace is allowed after "From", "to" etc.
lasseespeholt