简体   繁体   English

从大字符串C#中提取子字符串?

[英]Extracting substrings from large string C#?

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. 有人可以建议一些模式匹配机制。

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 subStr将是Item.Price|Item.Rate|Item.QTY

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM