简体   繁体   中英

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})

with regex

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

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\\.", "");

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.

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM