2014-01-24 116 views
4

我有一个样本字符串数据从大字符串C#中提取子字符串?

string state="This item (@"Item.Price", "item") is sold with an price (@"Item.Rate", "rate") per (@"Item.QTY", "Qty")"; 

我想要的输出

string subStr="Item.Price|Item.Rate|Item.QTY" 

是否有人可以提出一些解决方案。我正在尝试从File读取这些数据。 我有这样

if (!string.IsNullOrEmpty(state) && state != null) 
     { 
      while (state.IndexOf("Value(@\"") > 0) 
      { 
       int firstindex = state.IndexOf("(@\""); 
       int secondindex = state.IndexOf("\", \""); 
       if (firstindex > 0 && secondindex > 0) 
       { 
        keys.Add(state.Substring(firstindex + 3, secondindex - firstindex - 8)); 
        state = state.Substring(secondindex + 3); 
       } 
      } 

     } 

示例代码当数据较大,则抛出此异常:

Length cannot be less than zero 

有人可以建议一些这方面的模式匹配的机制。

+1

你应该使用正则表达式 – giammin

+3

的错误是不是因为你的“数据大” - 错误是很清楚,你是传递一个数字小于零作为“Substring”的第三个参数。想想secondindex - firstindex - 8可能最终会小于零,并解决这个问题。顺便说一下,你的示例字符串不包含'Value(@“'... – AakashM

+0

一般检查> = 0。它可能会找到第一个位置(0)的字符串。也许不是在这种情况下-1表示未找到。 – Frode

回答

4
var subStr = String.Join("|", Regex.Matches(state, @"@\""([\w\.]+)\""") 
           .Cast<Match>() 
           .Select(m => m.Groups[1].Value)); 

SUBSTR将Item.Price|Item.Rate|Item.QTY

0

试试这个

string state="This item (@\"Item.Price\", \"item\") is sold with an price (@\"Item.Rate\", \"rate\") per (@\"Item.QTY\", \"Qty\")"; 

var regex=new Regex("\\(@\"(?<value>.*?)\","); 

string.Join(
      "|", 
      regex.Matches(state).Cast<Match>().Select(m => m.Groups["value"].Value) 
      ); 
相关问题