无法删除c#中值之间的某些字符[重复]

时间:2021-07-31 02:24:36

This question already has an answer here:

这个问题在这里已有答案:

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

我试图删除从(包括)rgm到(和包括)的字符; 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.

注意:只有rgm和; 1。将保持静态,它们之间的字符会有所不同。

2 个解决方案

#1


2  

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

我建议将Regex用于此目的。尝试这个:

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:

Regex.Replace的第二个参数采用包含以下内容的模式:

  • rgm (your starting string)
  • rgm(你的起始字符串)
  • . (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)
  • 1。 (你的结束字符串 - 需要转义的点,否则就意味着任何字符)

#2


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.

您需要使用RegEx,其表达式为“rgm(。); 1 \。”。这只是我的头脑,你必须验证与你的模式匹配的确切正则表达式。然后,使用RegEx.Replace()。

#1


2  

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

我建议将Regex用于此目的。尝试这个:

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:

Regex.Replace的第二个参数采用包含以下内容的模式:

  • rgm (your starting string)
  • rgm(你的起始字符串)
  • . (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)
  • 1。 (你的结束字符串 - 需要转义的点,否则就意味着任何字符)

#2


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.

您需要使用RegEx,其表达式为“rgm(。); 1 \。”。这只是我的头脑,你必须验证与你的模式匹配的确切正则表达式。然后,使用RegEx.Replace()。