[英]Extracting substrings from large string 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"
有人可以建议一些解决方案。 我试图从文件中读取这些数据。 我有示例代码
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
有人可以建议一些模式匹配机制。
var subStr = String.Join("|", Regex.Matches(state, @"@\""([\w\.]+)\""")
.Cast<Match>()
.Select(m => m.Groups[1].Value));
subStr将是Item.Price|Item.Rate|Item.QTY
试试这个
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.