我有以下字符串:
[{names: {en: "US 30 - 5 Minute Level", es: "US 30 - 5 Minute Level"}, status: "A", displayed: "Y", start_time: "2011-05-20 00:00:00", start_time_xls: {en: "20th of May 2011 00:00 am", es: "20 May 2011 00:00 am"}, suspend_at: "2011-05-20 16:53:48", is_off: "Y", score_home: "", score_away: "", bids_status: "", period_id: "", curr_period_start_time: "", score_extra_info: "", settled: "N", ev_id: 2688484, ev_type_id: 10745, num_mkts: 5, venues: {en: "", es: ""}, disporder: 2040, ev_stream_available: false}]
我需要用引号括住所有变量名,这样就会验证为JSON。我正在做以下事情,但它也分开了日期。 。
Regex.Replace(input, @"(\w+:)", "\"$0\":", RegexOptions.None);
Regex.Replace之后的输出:
[{"names" {"en" "US 30 - 5 Minute Level", "es" "US 30 - 5 Minute Level"}, "status" "A", "displayed" "Y", "start_time" "2011-05-20 "00""00"00", "start_time_xls" {"en" "20th of May 2011 "00"00 am", "es" "20 May 2011 "00"00 am"}, "suspend_at" "2011-05-20 "16""53"48", "is_off" "Y", "score_home" "", "score_away" "", "bids_status" "", "period_id" "", "curr_period_start_time" "", "score_extra_info" "", "settled" "N", "ev_id" 2688484, "ev_type_id" 10745, "num_mkts" 5, "venues" {"en" "", "es" ""}, "disporder" 2040, "ev_stream_available" false}]
如何更改此选项以忽略它们?此外,什么是一个良好的基于Web的资源,一劳永逸地到达正则表达式的底部?!
感谢。
答案 0 :(得分:3)
尝试这种模式:
string pattern = @"\b([A-Za-z_]+)\b(?=:)";
string replace = "\"$0\"";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);
[A-Za-z_]+
匹配任何大写/小写字母和下划线字符一次或多次。如果没有JSON名称包含数字,则此方法正常。 \b
元字符匹配单词边界,(?=:)
匹配 - 但不捕获 - 冒号。您会注意到replace
模式不包含冒号。
同样,这种模式可以起作用:@"\b([^\d\s]+)\b(?=:)"
因为它匹配的不是数字或空格。
学习正则表达式需要大量练习来理解概念,尝试示例,并围绕事物的工作方式。我建议抓一个工具,让你试试看它们和一些教程。为了帮助您入门:
这应该让你开始。如果你真的想深入了解,那么请查看两本好书: