如何在特定字符串中获取字符串?

时间:2018-04-21 16:19:04

标签: c#

假设我有这个字符串:

string test = "var block = new MatchesBlock('page_competition_1_block_competition_matches_summary_5', 'block_competition_matches_summary', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13});"

如何获取MatchesBlock内的内容? 特别是这个json:

'page_competition_1_block_competition_matches_summary_5', 'block_competition_matches_summary', {"page":0,"bookmaker_urls":{"13":[{"link":"http:\/\/www.bet365.com\/home\/?affiliate=365_178981","name":"Bet 365"}]},"block_service_id":"competition_summary_block_competitionmatchessummary","round_id":42011,"outgroup":false,"view":2,"competition_id":13}

2 个答案:

答案 0 :(得分:1)

您应该使用正则表达式。为了达到您的特定结果,您可以执行以下操作:

var regex = new Regex(@"MatchesBlock\(([^)]+)\)");
foreach (Match match in regex.Matches(@"var block = new MatchesBlock('page_competition_1_block_competition_matches_summary_5', 'block_competition_matches_summary', {""page"":0,""bookmaker_urls"":{""13"":[{""link"":""http:\/\/www.bet365.com\/home\/?affiliate=365_178981"",""name"":""Bet 365""}]},""block_service_id"":""competition_summary_block_competitionmatchessummary"",""round_id"":42011,""outgroup"":false,""view"":2,""competition_id"":13});")) {
    var yourtext = match.Groups[1].Value;
}

这个正则表达式可以分解为:

  1. MatchesBlock\( - >将文本匹配到左括号
  2. ( - >启动捕获组
  3. [^)]+ - >捕获不是右括号的所有内容
  4. ) - >结束捕获组
  5. \) - >匹配右括号
  6. 但你的方法很幼稚。你应该使用更强大的东西,比如特定语言的解析器(看起来像JavaScript)。除非你真的,真的只需要这个价值。

    在不知道你的确切要求的情况下,坐在这里,远远望去,里约热内卢的秋日阳光照耀着我的窗户,这对我来说就像code smell。是不是有另一种方法可以避免解析源代码?

答案 1 :(得分:0)

这样就够了吗?

var startTrimmed = test.Replace("var block = new MatchesBlock(", string.Empty");
var endTrimmed = startTrimmed.Replace(");", string.Empty);