2009-09-21 128 views
1

我具有基于一组值对我所分割字符串- C#,与分割字符串

string[] seperator = new string[9]; 
     seperator[0] = "*"; //is the client 
     seperator[1] = "/"; //is the name of company 
     seperator[2] = "(";  //name of the market  
     seperator[5] = ":"; //ID 
     seperator[6] = "?"; //orderType 
     seperator[3] = "[email protected]"; //realtive Time 
     seperator[4] = "!+"; // 
     seperator[7] = "+"; //quantity 
     seperator[8] = "@";//price 
string[] result = values.Split(seperator, StringSplitOptions.None); 

例如问题:输入字符串是 * A/AB(M @ 12:6? !SIMPLE + 5 + 2

 
OUTPUT 
    [0]: "" 
    [1]: "A" 
    [2]: "AB" 
    [3]: "M" 
    [4]: "12" 
    [5]: "6" 
    [6]: "SIMPLE" 
    [7]: "5" 
    [8]: "2" 

例如:!?!输入字符串是 * A(M @ 12 SIMPLE + 5 + 2/AB:6

 
OUTPUT: 
    [0]: "" 
    [1]: "A" 
    [2]: "M" 
    [3]: "12" 
    [4]: "SIMPLE" 
    [5]: "5" 
    [6]: "2" 
    [7]: "AB" 
    [8]: "6" 

我面临的问题是:我怎么能说,A是客户,AB是公司等等

作为用户可以输入这个信息的顺序RANDOM ... 如果他没有进入这些值中的任何一个,它会改变结果长度?

+0

如果没有标记标识字段和字段顺序是随机的,我不明白你将如何去做 –

+0

对不起,我只看到noe有标识符 –

回答

1

使用这样的事情

SortedList<int, string> list = new SortedList<int, string>(); 
      string[] seperator = new string[9]; 
      seperator[0] = "*"; //is the client 
      seperator[1] = "/"; //is the name of company 
      seperator[2] = "(";  //name of the market  
      seperator[5] = ":"; //ID 
      seperator[6] = "?"; //orderType 
      seperator[3] = "[email protected]"; //realtive Time 
      seperator[4] = "!+"; // 
      seperator[7] = "+"; //quantity 
      seperator[8] = "@";//price 
      string val = "*A/AB([email protected]:6?SIMPLE!+5+2"; 

      for (int iSep = 0; iSep < seperator.Length; iSep++) 
       list.Add(val.IndexOf(seperator[iSep]), val); 

会给你在分隔符开始位置的列表,以任意顺序的用户输入,然后你可以使用子检索值

+0

伟大的...工作!谢谢astander和orsogufo –

5

如何使用一个或多个具有命名捕获组的正则表达式并按名称对匹配建立索引?

检查例如this msdn pagethis post

下面是一个例子,让你开始:

using System; 
using System.Text.RegularExpressions; 

class Program { 
    static void Main(string[] args) { 

     Regex regex = new Regex(@"(?:\*(?<client>\w+))|(?:/(?<company>\w+))",RegexOptions.Compiled); 
     string input = "*A/AB([email protected]:6?SIMPLE!+5+2"; 

     foreach (Match match in regex.Matches (input)) { 
      if (match.Groups["client"].Success) { 
       Console.WriteLine("Client = {0}", match.Groups["client"].Value); 
      } else if (match.Groups["company"].Success) { 
       Console.WriteLine("Company = {0}", match.Groups["company"].Value); 
      } 
     } 


    } 
} 

我知道,正则表达式的语法似乎很难在第一理解,但他们是一支非常强大的工具时,你需要这样做一种文本操作。

此外,还有一些工具可以让您尝试并帮助您编写正则表达式,例如ExpressoThe Regulator

3

什么在输入字符串上执行多个Replaces以将其变为更易于管理的格式。例如。

inputString = inputString.Replace("*", ",Client=").Replace("/", ",Company="); 

那么可以拆分上“”和让你与他们的标题字符串列表,然后拆分那些‘=’,以获得标题和值。

+0

这个人也工作了!谢谢 –