3

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.

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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 :)
Okay cool, I can make it more strict with regards to parentheses etc.
My fault, I can also have numbers before the first brackets, so this isn't exactly the right solution... Edited first post.
Okay, I have edited the post now (all of it) it works with your examples.
I have changed it again. It worked fine before, but I have made so more than one whitespace is allowed after "From", "to" etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.