如何替换部分未知字符串

Tel*_*sch 1 c# string-operations


我需要替换(或更好地删除)字符串,在此我知道开始和结束。
有些字符是未知的,字符串的长度也是未知的。
当然,我可以使用子字符串和其他c#字符串操作,但是没有简单的替换通配符选项吗?

mystring.Replace("O(*)", "");
Run Code Online (Sandbox Code Playgroud)

Would be a nice Option.
I know that the string Begins with O( and Ends with ).
It's possible than the String Looks like O(something);QG(anything else)
Here the result should be ;QG(anything else)

Is this possible with a simple replace?
And what About the advanced Option, that he string exists more than one time like here:
O(something);O(someone);QG(anything else)

Cai*_*ard 6

Take a look at regular expressions.

The following will meet this case:

var result = Regex.Replace(originalString, @"O\(.*?\)", "");
Run Code Online (Sandbox Code Playgroud)

What it means:

  • @ - switch off C# interpreting \ as escape, because otherwise the compiler will see our \( and try to replace it with another char like it does for \n becoming a newline (and there is no \( so it's a compiler error). Regex also uses \ as an escape char, so without the @ to get a slash into the string for regex to interpret as a slash to perform a regex escape, it needs a double C# slash, and that can make regex patterns more confusing
  • " start of c# string
  • O\( literal character O followed by literal character ( - brackets have special meaning in regex, so backslash disables special meaning)
  • .*? match zero or more of any character (lazy/pessimistic)
  • \) literal )
  • " end of string

.*? is a complex thing warrants a bit more explanation:

In regex . means "match any single character", and * means "zero or more of the previous character". In this way .* means "zero or more of any character".

So what's the ? for?

By default regex * is "greedy" - a .* with eat the entire input string and then start working backwards, spitting characters back out, and checking for a match. If you had 2 in succession like you put:

K(hello);O(mystring);O(otherstring);L(byebye)
Run Code Online (Sandbox Code Playgroud)

And you match it greedily, then O\(.*\) will match the initial O(, then consume all the input, then spit one trailing ) back out and declare it's found a match, so the .* matches mystring);O(otherstring;L(byebye

我们不想要这个。相反,我们希望它一次转发一个字符,以寻找匹配项)。将?后面的内容*从贪婪模式更改为悲观(/ lazy)模式后,将向前扫描输入,而不是将其压缩到末尾并向后扫描。这意味着,O\(.*?)比赛mystring,再后来otherstring,留下的结果K(hello);;;L(byebye),而不是K(hello);