从主字符串中提取子字符串的值

本文关键字:字符串 提取 | 更新日期: 2023-09-27 18:10:00

我有一个像下面提到的字符串。

{
    behavior_capture_widget: "<div id="ndwc"><noscript><input type="hidden" id="ndpd-spbd" name="ndpd-spbd"                            value="ndpds~~~2.4177.112540pPaGJYVmt5WCtndGlUiUcRt3aSOPQ,,"></noscript></div> <script type="text/javascript"></script>"
    customer_session_data:   "2.4177.112540.1399312572.2.mFDzrW_JJeu-C_H45O5ADQ"
    customer_cookie_data:    "2.4177.112540.1399312572.2.XYjAsjFsOVHFXBGNnnHc-g,,."
}

我将总是得到这种格式的字符串。

我必须提取

的值
behavior_capture_widget
customer_session_data
customer_cookie_data
变量a,b,c 中的

我是c#的新手,我试图使用substring(), indexof()的组合,但无济于事如果你能帮忙,我将不胜感激。

从主字符串中提取子字符串的值

您可以使用string代替substring。分割,让你的大部分方式:

var input = "... your data ...";
var valueNames = new [] 
{
    "behavior_capture_widget:", 
    "customer_session_data:", 
    "customer_cookie_data:"
};
var items = input.Split(valueNames, StringSplitOptions.RemoveEmptyEntries);

现在你可以提取你的值了:

var behaviorCaptureWidget = items[1].Trim();
var customerSessionData= items[2].Trim();
var customerCookieData= items[3].Trim().Replace("'"}", "");

注意最后一个需要手动删除尾部的"}

如果在执行之前不知道key: value对中的键的名称,或者不知道期望键的顺序,则可以使用正则表达式和字典来存储任何键-值对:

class StrangeParser
{
    public static readonly Regex LINE_REGEX = new Regex("^''s*([a-zA-Z0-9_]+)''s*'':''s*'"(.*)'"''s*$", RegexOptions.Multiline);
    public static Dictionary<string, string> ParseStr(string str)
    {
        var m = LINE_REGEX.Matches(str);
        var res = new Dictionary<string, string>();
        foreach (Match item in m)
        {
            res.Add(item.Groups[1].Value, item.Groups[2].Value);
        }
        return res;
    }
    static void Main(string[] args)
    {
        foreach (var item in ParseStr(@"
{
    behavior_capture_widget: ""<div id=""ndwc""><noscript><input type=""hidden"" id=""ndpd-spbd"" name=""ndpd-spbd""                            value=""ndpds~~~2.4177.112540pPaGJYVmt5WCtndGlUiUcRt3aSOPQ,,""></noscript></div> <script type=""text/javascript""></script>""
    customer_session_data:   ""2.4177.112540.1399312572.2.mFDzrW_JJeu-C_H45O5ADQ""
    customer_cookie_data:    ""2.4177.112540.1399312572.2.XYjAsjFsOVHFXBGNnnHc-g,,.""
}
"))
        {
            Console.WriteLine(item.Key + " " + item.Value);
        }
    }
}

如果是JSON总是。我认为最好使用"Json"。网":

string json = @"{
  {
       behavior_capture_widget: "<div id='"ndwc'"><noscript><input type='"hidden'" id='"ndpd-spbd" name='"ndpd-spbd'"                            value='"ndpds~~~2.4177.112540pPaGJYVmt5WCtndGlUiUcRt3aSOPQ,,'"></noscript></div> <script type='"text/javascript'"></script>"
       customer_session_data:   "2.4177.112540.1399312572.2.mFDzrW_JJeu-C_H45O5ADQ"
       customer_cookie_data:    "2.4177.112540.1399312572.2.XYjAsjFsOVHFXBGNnnHc-g,,."
 }";
Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var mydata = dict["customer_cookie_data"]; // extraction

看这里

如果您要广泛使用这种格式,那么为这种语法设计一个解析器可能是值得的。

可以使用解析器组合子来定义语法树。

使用Sprache,我构建了这个解析器,它给了你一个Dictionary<string, string>:

var key = Parse.CharExcept(c => char.IsWhiteSpace(c) || c == ':', "").Many().Text();
var value =
    from leading in Parse.Char('"')
    from val in Parse.AnyChar.Until(Parse.Char('"').Then(_ => Parse.LineEnd)).Text()
    select val;
var separator =
    from x in Parse.WhiteSpace.Many()
    from colon in Parse.Char(':')
    from y in Parse.WhiteSpace.Many()
    select colon;
var keyValue =
    from k in key
    from s in separator
    from v in value
    select new KeyValuePair<string, string>(k, v);
var parser =
    from open in Parse.Char('{').Then(_ => Parse.WhiteSpace.Many())
    from kvs in keyValue.DelimitedBy(Parse.WhiteSpace.Many())
    from close in Parse.WhiteSpace.Many().Then(_ => Parse.Char('}'))
    select kvs.ToDictionary(kv => kv.Key, kv => kv.Value);

你现在可以这样使用这个解析器:

var dictionary = parser.Parse(input);