【问题标题】:How to get js code from regex?如何从正则表达式中获取 js 代码?
【发布时间】:2017-10-27 13:06:26
【问题描述】:

我是正则表达式的新手,我不会过多地使用这种语言。 我正在尝试在此代码中获取competition_id

    <script type="text/javascript" charset="utf-8">

      (function() {
          var block = new MatchesBlock('page_team_1_block_team_matches_summary_7', 'block_team_matches_summary', {"page":0,"bookmaker_urls":[],"block_service_id":"team_summary_block_teammatchessummary","team_id":1242,"competition_id":0,"filter":"all","new_design":false});
          block.registerForCallbacks();
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_1', 'changeCompetition', {"competition_id":0});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_2', 'changeCompetition', {"competition_id":13});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_3', 'changeCompetition', {"competition_id":135});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_4', 'changeCompetition', {"competition_id":171});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_5', 'changeCompetition', {"competition_id":1148});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_6', 'changeCompetition', {"competition_id":732});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_1_7', 'changeCompetition', {"competition_id":10});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_2_1', 'filterMatches', {"filter":"all"});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_2_2', 'filterMatches', {"filter":"home"});
          block.addCallbackObserver('page_team_1_block_team_matches_summary_7_2_3', 'filterMatches', {"filter":"away"});

          block.setAttribute('colspan_left', 4);
          block.setAttribute('colspan_right', 3); 
          block.setAttribute('has_previous_page', true);
          block.setAttribute('has_next_page', true);
          TimestampFormatter.format('page_team_1_block_team_matches_summary_7');
                })();
    </script>

链接是这样的: 查看源代码:http://it.soccerway.com/teams/italy/juventus-fc/1242/

到目前为止我所做的是:

var c = System.Text.RegularExpressions.Regex.Match(data, "'block_team_matches_summary', (\\{.*?\\})\\);\\n", 
            System.Text.RegularExpressions.RegexOptions.Singleline).Groups[1].Value;

这个正则表达式应该返回所有可用的块,但它只返回第一个元素:

{"page":0,"bookmaker_urls":[],"block_service_id":"team_summary_block_teammatchessummary","team_id":1244,"competition_id":0,"filter":"all","new_design":false}

我需要得到所有的积木,我能做什么?

【问题讨论】:

  • “所有块”是什么意思?在'block_team_matches_summary', 之后只有一个{...} 子字符串,并且您成功提取它。
  • @WiktorStribiżew 如果你看到函数的内容它包含一个块列表,例如:page_team_1_block_team_matches_summary_7page_team_1_block_team_matches_summary_7_1_1page_team_1_block_team_matches_summary_7_1_2,每个块包含不同的id

标签: javascript c# html regex


【解决方案1】:

首先,我推荐Expresso。它是免费的,但您必须注册它。我发现它对于使用正则表达式以及学习更好地使用它们都非常有价值。最后一个警告是,使用正则表达式(尤其是网页内容;这就是您的内容)解析字符串特别脆弱并且很容易中断。如果文本有微小的变化,现在可以使用的正则表达式很容易开始失败。

说完,现在来回答您的具体问题。我假设您正在寻找的结果集是 0,13,135,171,1148,732,10(所有比赛 id)

我们将首先打开 Expresso 并将所有文本粘贴到示例文本(左下角)区域(确保您位于测试模式选项卡上)。现在我们将开始编写一个正则表达式来查找我们正在寻找的文本。将competition_id": 放入正则表达式区域(左上角)。如果您在 Regex Analyzer(右上角)中展开树,它将显示每个单独的字符。这表明所有这些字符都将按字面意思匹配。如果单击“运行匹配”按钮,您将在“搜索结果”中看到匹配列表(右下角)。完美,它找到了该文本出现的所有 8 个区域。您可以单击每个搜索结果,Expresso 将突出显示示例文本中的相应区域。 现在我们需要扩展它以匹配它后面的数字。如果单击“设计模式”选项卡,您将在底部看到一个区域,其中列出了所有正则表达式符号及其含义。我发现这个区域有助于查找各种匹配模式。将正则表达式改为competition_id":\d+

\d 表示匹配任意数字 (0-9),+ 表示匹配其中一个或多个。如果您单击运行匹配,您将看到每个匹配现在都包含文本 competition_id:"&lt;number&gt;

如果我们在 C# 中使用这个正则表达式,它将返回所有文本,在这种情况下我们只需要数字。对正则表达式 competition_id":(\d+) 的最后一项更改。请注意,在 Regex Analyzer 中,它现在表明我们有一个数字捕获组。这意味着括号内的匹配部分将被放入我们可以轻松提取的自己的组中。单击运行匹配,您会注意到匹配仍然包含全文匹配,但现在每个匹配下都有一个包含单个值的子组。

现在回到 C#,我会假设你是一个名为 data 的字符串值中的大脚本块。

string data = ...;
//Get all of the matches
MatchCollection matches = Regex.Matches(data, "competition_id\":(\\d+)");
foreach (Match match in matches)
{
    //This is the group number that we saw in expression. Group[0] will be the full match.
    Group group = match.Groups[1]; 
    //Get the value out of the group. We can do an int.Parse since we know it will only contian digits
    int competition_id = int.Parse(group.Value);
    //TODO: Do something with competition_id
}

注意:当正则表达式表示为字符串时,我们必须对其进行转义。

这只是对正则表达式的一个小介绍。我会鼓励你玩转 Expresso 并在网上闲逛。那里有很多好的资源。最重要的是练习。

【讨论】:

  • 嗨,感谢您的精彩回答,不幸的是我得到了matches.Count = 0;数据内容是这样的:pastebin.com/AS7vMBYq
  • 抱歉,当我将正则表达式模式移到 C# 中时,出现了一个小错字。我不小心在\d+ 之间放了一个空格。这会导致正则表达式失败,因为 + 只影响它之前的东西(这是空格,而不是预期的 \d。更新后的代码应该可以工作。
  • 另一种选择是使用HTMLAgilityPack 和(Jurassic library 或 XPath)来获得你想要的。
【解决方案2】:

"competition_id":(\d+) 应该可以解决问题

查看here

【讨论】:

    【解决方案3】:

    以下将删除所有多余的字符,例如“{} :

                string input = "{\"page\":0,\"bookmaker_urls\":[],\"block_service_id\":\"team_summary_block_teammatchessummary\",\"team_id\":1244,\"competition_id\":0,\"filter\":\"all\",\"new_design\":false}";
                input.Replace("{", "");
                input.Replace("}", "");
                string[] groups = input.Split(new char[] { ',' });
    
                string pattern = "\"(?'name'[^:]+)\":(?'value'.*)";
                foreach (string group in groups)
                {
                    string data = group.Replace("\\","");
                    Match regData = Regex.Match(data, pattern);
                    Console.WriteLine("name : '{0}', value : '{1}'", regData.Groups["name"].Value, regData.Groups["value"].Value.Replace("\"",""));
    

    【讨论】:

    • 但这并没有得到所有的块,或者我错过了什么?
    • for 循环获取的是块。字符串拆分创建一个数组 group[]。这个帖子比花括号、双引号和一些值是字符串和其他数字看起来更复杂。我的代码适用于所有条件。
    【解决方案4】:

    您需要使用Regex.Matches 而不是Regex.Match

    请参考以下讨论。 How to find multiple occurrences with regex groups?

    要在 JavaScript 中执行此操作,您可以参考以下讨论。 Javascript regex get an array of all matches, not just the first occurance

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      相关资源
      最近更新 更多