如何从字符串中删除字符序列

时间:2017-06-10 14:21:59

标签: c# string

我想从给定的字符串A中删除未知数量的字符序列B. 删除必须从字符序列C的位置右侧开始。当B字符序列结束时,删除必须停止。

字符串A:

的示例
xxxxxxxxBxxxxxxxxxxxxxxxxxCBBBBBByyyyyyyyyByyyy

A ... sequence of characters from which B's that follow C must be removed
C ... a sequence of characters (example: 123)
B ... a sequence of characters (example: vbz)
x and y ... any characters

在此示例中,必须删除C之后的所有B。不得删除所有其他B。

结果将是:

xxxxxxxxBxxxxxxxxxxxxxxxxxCyyyyyyyyyByyyy

我试图使用:

A = A.replace("vbz","");

但这会删除所有' vbz'来自A的序列 如何排除删除那些' vbz'那些不是C?

问候,Manu

3 个答案:

答案 0 :(得分:1)

为什么不试试这个?

var.Replace("x", "");
var.Replace("y", "");

只需将xy替换为未知字符串序列

即可

答案 1 :(得分:1)

string A = "xxxxxxxxBxxxxxxxxxxxxxxxxxCBBBBBByyyyyyyyyByyyy";
string pattern = @"(?<=C)[B]*";
string B = Regex.Replace(A, pattern, "");

答案 2 :(得分:0)

As per your requirement, 2 conditions need to be satisfied for removing from a string :

1. unknown number of string sequences B
2. The removing must start to the right of the position of a string C

It can be achieved using Regex class of System.Text.RegularExpressions namespace.

string A = "xxxxxxxxBxxxxxxxxxxxxxxxxxCBBBBBByyyyyyyyyByyyy";
string pattern = "(?<=C)[b]*";
string result = Regex.Replace(A, pattern,"",RegexOptions.IgnoreCase);


Note :
pattern variable contains regex pattern.
(cb*) : 
() : defines group of characters
c : starting string
b : B or b ; i.e, need to be replaced or removed
* : defines multiple number of characters defines before *
(?<=c) : Match any position following a prefix "c"
RegexOptions.IgnoreCase : it says the removed character can be any case like B or b