Extract substrings from C # big string?

I have an example of string data

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

I want the result to be

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

Can anyone suggest some solution. I am trying to read this data from a 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, this is an exception:

 Length cannot be less than zero

Can anyone suggest a pattern matching mechanism for this?

+4
source share
2 answers
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

+4
source

try it

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)
           );
0
source

Source: https://habr.com/ru/post/1523491/


All Articles