JJ.
JJ.

Reputation: 9950

How to get a string between 2 specific characters in C#

Having a hard time with Regex.

I have this string:

I need to replace this whole number "11.000000" with another number.

How do I identify this string by saying:

Give me the string right before "%" until you reach the first blank space (" ")?

Upvotes: 0

Views: 71

Answers (3)

rory.ap
rory.ap

Reputation: 35260

Try this:

string pattern = @"^Fixed Breakeven with (\d+(\.\d+)?)% Fees$";
string input = "Fixed Breakeven with 11.0000000% Fees";

var match = Regex.Match(input, pattern);
string output = string.Empty;

if (match != null)
{
    output = match.Groups[1].Value;
}

Produces 11.0000000.

Upvotes: 1

Vivek Nuna
Vivek Nuna

Reputation: 1

You can try this also, using regex. This is generic method to fetch decimal from string. It will work for all cases.

public static bool ExtractDecimalFromString(string inputString, out Decimal decimalValue)
    {
        Regex regex = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*");
        Match match = regex.Match(inputString);
        decimalValue =  match.Success ? Convert.ToDecimal(match.Groups[1].Value) : 0;
        return match.Success;
    }

Upvotes: 1

MacakM
MacakM

Reputation: 1820

You can use LINQ:

var myString = "Fixed Breakeven with 11.0000000% Fees";
var number = myString.Split('%').First().Split(' ').Last();

Upvotes: 1

Related Questions