0

I am trying to remove characters starting from (and including) rgm up to (and including) ;1..

Example input string:

Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value})

Code:

string strEx = "Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value})";
strEx = strEx.Substring(0, strEx.LastIndexOf("rgm")) + 
        strEx.Substring(strEx.LastIndexOf(";1.") + 3);

Result:

Sum ({rgmdaerub;1.Total_Value}, {.Major_Value})

Expected result:

Sum ({Total_Value}, {Major_Value})

Note: only rgm and ;1. will remain static and characters between them will vary.

mikemind
  • 49
  • 1
  • 9
  • Please rewrite this as a [mcve]. It's hard to follow "code, results, code" rather than "all the code, ready to run; results". (Fundamentally this feels like a regex would be more useful here... How are you expecting that code running *once* to replace *two* values?) – Jon Skeet Nov 23 '16 at 11:13
  • 1
    How about `strEx = strEx.Replace("rgmdaerub;1.", "")` – Alfie Goodacre Nov 23 '16 at 11:14
  • Sorry I'm a beginner, but why do you write your solution as a comment? – Mitulát báti Nov 23 '16 at 11:15
  • @AlfieGoodacre - only `rgm` and `;1.` will remain static and characters between them will vary. – mikemind Nov 23 '16 at 11:15
  • @Mitulátbáti for the reason that has just become clear, I was not 100% sure that it would answer OP's question, so I commented it in case - it also isn't a full answer but more of a suggestion :) – Alfie Goodacre Nov 23 '16 at 11:16
  • @mikemind In that case, you could try a regex replace - `Regex rX = new Regex(@"rgm\w+;1\.");` and then `strEX = rX.Replace(strEx, "");`. This assumes that only letters will be in between – Alfie Goodacre Nov 23 '16 at 11:20

2 Answers2

2

I would recommend to use Regex for this purpose. Try this:

string input = "Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value})";
string result = Regex.Replace(input, @"rgm.*?;1\.", "");

Explanation:

The second parameter of Regex.Replace takes the pattern that consists of the following:

  • rgm (your starting string)
  • . (dot - meaning any character)
  • *? (the preceding symbol can occure zero or more times, but stops at the first possible match (shortest))
  • ;1. (your ending string - the dot needed to be escaped, otherwise it would mean any character)
Mitulát báti
  • 2,086
  • 5
  • 23
  • 37
1

You need to use RegEx, with an expression like "rgm(.);1\.". That's just off the top of my head, you will have to verify the exact regular expression that matches your pattern. Then, use RegEx.Replace() with it.

Tsahi Asher
  • 1,767
  • 15
  • 28