mikemind
mikemind

Reputation: 49

Remove characters between in c#

I have a string values like this

string strValue = "!return.ObjectV,rgmK12D;1.Value";

In this string how can I remove characters from rgm to ;1?

Below code will remove all the characters from rgm, but I need to remove upto ;1 only

strValue =  strValue.Substring(0, strValue.LastIndexOf("rgm"));

Expected Result:

string strValue = "!return.ObjectV,.Value";

Edit 1:

I am trying to remove the above mentioned characters from the below string

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

Result

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

Expected Result

Sum ({Total_Value}, {Major_Value})

Upvotes: 0

Views: 2068

Answers (5)

Thejaka Maldeniya
Thejaka Maldeniya

Reputation: 1076

A simple solution would be:

strValue = strValue.Substring(0, strValue.LastIndexOf("rgm")) + strValue.Substring(strValue.LastIndexOf(";1") + 2);

EDIT:

According to your edit, it seems you want all occurrences replaced. Also, your expected result has the "." removed as well. To replace all occurrences you can adapt from @Damith's answer:

strValue = Regex.Replace(strValue, "rgm.*?;1\\.", "");

Upvotes: 1

anilg
anilg

Reputation: 1

You can use string.IndexOf() and string.Replace()

        var i = strValue.IndexOf("rgm");
        var j = strValue.IndexOf(";1");
        var removePart = strValue.Substring(i, j - i);
        strValue.Replace(removePart, string.Empty);

Upvotes: 0

Damith
Damith

Reputation: 63105

with regex

string strValue = "!return.ObjectV,rgmK12D;1.Value";
var output = Regex.Replace(strValue, @" ?rgm.*?;1", string.Empty);
// !return.ObjectV,.Value

Upvotes: 1

fofik
fofik

Reputation: 1008

You can use something like this. First find "rgm" and ";1" position, then remove characters between these indexes.

int start = strValue.LastIndexOf("rgm");
int end = strValue.LastIndexOf(";1");
string str = strValue.Remove(start, (end-start)+2);

Upvotes: 0

Emad
Emad

Reputation: 3949

One way is to do it like this:

strValue =  strValue.Substring(0, strValue.LastIndexOf("rgm")) +
    strValue.Substring(strValue.LastIndexOf(";1"), strValue.Length);

This way you get the first part and the second part then concatenate them together. This will work if you have only one instance of these characters.

Upvotes: 0

Related Questions