4

I have an sample string data

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

I want the output as

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

Can someone please suggest some solution. I am trying to read this data from File. I have sample code like

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);
                }
            }

        }

When data is large then this exception is thrown:

 Length cannot be less than zero

Can somebody suggest some pattern matching mechanism for this.

  • 1
    you should use regexp – giammin Jan 24 '14 at 09:55
  • 3
    The error is not because your "data is large" - the error is quite clear that you are passing a number less than zero as the third parameter to `Substring`. Think about how `secondindex - firstindex - 8` might end up being less than zero, and solve that problem. By the way, your sample string doesn't include `Value(@"` at all... – AakashM Jan 24 '14 at 09:59
  • In general check for >= 0. It might find the string in the first position (0). Maybe not in this case though. -1 means not found. – Frode Jan 24 '14 at 10:05
  • Check this SO question: http://stackoverflow.com/questions/21095082/conversion-from-string-to-object-in-windows-8-1-store-app-c-sharp/21095365#21095365 – Muhammad Umar Jan 24 '14 at 10:06

2 Answers2

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

subStr will be Item.Price|Item.Rate|Item.QTY

L.B
  • 114,136
  • 19
  • 178
  • 224
0

Try this

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)
           );
Bob Vale
  • 18,094
  • 1
  • 42
  • 49