DarrenL
DarrenL

Reputation: 43

Trying to extract code in the middle of a String

I am trying to extract a code from a string. The string can vary in content and size but I am using Tag words to make the extraction easier. However, I am struggling to nail a particular scenario. Here is the string:

({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}

What I need to extract is the 011 part of {MP.011}. The keyword will always be "{MP." It's just the code that will change. Also the rest of the expression can change so for example {MP.011} could be at the beginning, end or middle of the string.

I've got close using the following:

        int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
        int pTo = code.LastIndexOf("}");
        String result = code.Substring(pFrom, pTo - pFrom);

However, the result is 011} + {SilverPrice as it is looking for the last occurrence of }, not the next occurrence. This is where I am struggling.

Any help would be much appreciated.

Upvotes: 4

Views: 410

Answers (4)

John Alexiou
John Alexiou

Reputation: 29274

The key is to use the .IndexOf(string text,int start) overload.

static void Main(string[] args)
{
    string code = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";

    // Step 1. Extract "MP.011"
    int pFrom = code.IndexOf("{MP.");
    int pTo = code.IndexOf("}", pFrom+1);
    string part = code.Substring(pFrom+1, pTo-pFrom-1);
    // Step 2. Extact "011"
    String result = part.Substring(3);
}

or you can combine the last statements into

    String result = code.Substring(pFrom+1, pTo-pFrom-1).Substring(3);

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30663

the safest option is to use Regex with Negative and Positive Lookahead. This also matches multiple if you need it anyway.

  var str3 = @"({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
  var result = Regex.Matches(str3, @"(?<=\{MP\.).+?(?=\})");

  foreach (Match i in result)
  {
      Console.WriteLine(i.Value);
  }

Upvotes: 1

vinicius.ras
vinicius.ras

Reputation: 1606

You could use a regular expression to parse that:

var str = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var number = Regex.Match(str, @"{MP\.(\d+)}")
    .Groups[1].Value;
Console.WriteLine(number);

Upvotes: 4

Sria Pathre
Sria Pathre

Reputation: 182

        int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
        int pTo = code.IndexOf("}", pFrom); //find index of } after start
        String result = code.Substring(pFrom, pTo - pFrom);

Upvotes: 3

Related Questions