从字符串请求中获取特定字符

时间:2016-05-13 15:38:53

标签: c# substring

我需要从字符串中获取4个变量

这是某人可以向服务器发出的请求:

String request= "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>"

我需要nbtmisenumeros_grilleAnumeros_grilleB

3 个答案:

答案 0 :(得分:4)

您可以尝试使用正则表达式

  String request = "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>";

  String pattern = @"(?<=<)[^<>]*(?=>)";

  String[] prms = Regex
    .Matches(request, pattern)
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

测试:

  // nbT
  // mise
  // numeros_grilleA
  // numeros_grilleB
  Console.Write(String.Join(Environment.NewLine, prms));

答案 1 :(得分:0)

您需要解析请求。如何做到这完全取决于您希望收到的内容以及验证方式。假设(并且这是一个很大的假设)您将始终获得上面的格式,您可以使用String.Split将字符串拆分为开括号字符,然后取出组件(忽略第一个)并修剪掉关闭括号和任何其他空格。这些将是你的变量。无论如何,这不是一种发送数据的好方法,在使用数据之前,您至少应该对这些数据进行大量验证。

非常基本(并且无论如何这是你不应该使用的可怕代码)的概念是:

 String request= "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>";
 var pieces = request.Split('<');
 var strList = new List<string>();
 for(int i = 1 ; i < pieces.Length; i++)
 {
     strList.Add(pieces[i].Trim(' ','>'));
 }

答案 2 :(得分:-1)

String request = "Jouer_un_bulletin <nbT> <mise> <numeros_grilleA> <numeros_grilleB>";
var open = 0;
bool opened = false;
var results = new List<string>();
for (int i = 0; i < request.Length; i++)
{
    if (request[i] == '<')
    {
        opened = true;
        open = i;
    }
    if (request[i] == '>' && opened)
    {
        results.Add(request.Substring(open + 1, i - open - 1));
        opened = false;
    }
}
foreach(var item in results)
    Console.WriteLine(item);

输出:

nbT
mise
numeros_grilleA
numeros_grilleB
相关问题