获取两个字符串之间的子串

时间:2016-04-01 14:20:11

标签: c#

我有一个字符串:

string test1 = "The element 'Content' with the value 'blabla1' is invalid - The value 'nana1' is invalid";
string test2 = "The element 'Content' with the value ''blabla2'' is invalid - The value ''nana2'' is invalid";

我希望得到这样的结果:

1. blabla1 
2. blabla2

我的代码实际上是:

string result1 = test1.Split('\'', '\'')[3];
string result2 = test2.Split('\'', '\'')[3];

但实际得到的价值是:

1. blabla1
2. ''

我需要通过一种功能来解决这两种问题。我怎么能意识到这一点?提前谢谢!

4 个答案:

答案 0 :(得分:2)

跳过空项目,您可以使用 doubled &符号

// '\'' is a separator, you have no need to put it twice
// but put StringSplitOptions.RemoveEmptyEntries
// so empty lines created by doubled ampersands
// ''abc'' -> ["" , "abc", ""]
// will be removed
string result1 = test1
  .Split(new Char[] { '\'', }, StringSplitOptions.RemoveEmptyEntries)[3];

string result2 = test2
  .Split(new Char[] { '\'', }, StringSplitOptions.RemoveEmptyEntries)[3];

另一种可能性是在分析之前格式化文本,例如让我们将乘以的&符号转换为单个&符号:

String test1 = Regex.Replace(test1, "'{2,}", "'");
// "The element 'Content' with the value 'blabla2' is invalid - The value 'nana2' is invalid"
String test2 = Regex.Replace(test2, "'{2,}", "'");

然后使用SplitSubstring等。

答案 1 :(得分:1)

使用'' '作为分隔符,您应该能够解决此问题。

string test1 = "The element 'Content' with the value 'blabla1' is invalid - The value 'nana1' is invalid";
string test2 = "The element 'Content' with the value ''blabla2'' is invalid - The value ''nana2'' is invalid";

string result1 = test1.Split(new string[] { "''", "'" }, StringSplitOptions.None)[3];
string result2 = test2.Split(new string[] { "''", "'" }, StringSplitOptions.None)[3];

答案 2 :(得分:1)

因为blabla2在双引号内。所以使用

 string result2 = test2.Split('\'', '\"')[3];

答案 3 :(得分:1)

除了转义引号外,你应该在用单引号拆分时使用双引号,同样如果你想用双引号拆分,你应该使用单引号来开始和结束字符串。例如

string result1 = test1.Split(new string[] {"''", "'"})[3];
string result2 = test2.Split(new string[] {"''", "'"})[3];

您的另一个问题是,您的两个标准都是相同的,如果您不希望更改为双引号,则可能意味着第二个标准为'\'\''