【问题标题】:Is there a way to have a capture repeat an arbitrary number of times in a regex?有没有办法让捕获在正则表达式中重复任意次数?
【发布时间】:2009-08-24 16:42:03
【问题描述】:

我正在使用 C++ tr1::regex 和 ECMA 正则表达式语法。我要做的是解析一个标头并返回与标头中每个项目相关联的值。

标题:

-Testing some text
-Numbers 1 2 5
-MoreStuff some more text
-Numbers 1 10

我想做的是找到所有“-Numbers”行,并使用单个正则表达式将每个数字放入自己的结果中。如您所见,“-Numbers”行可以有任意数量的值。目前,我只是在搜索“-Numbers([\s0-9]+)”,然后对该结果进行标记。我只是想知道是否有任何方法可以在单个正则表达式中查找和标记结果。

【问题讨论】:

    标签: c++ regex capture


    【解决方案1】:

    不,没有。

    【讨论】:

      【解决方案2】:

      我正要问这个完全相同的问题,但我找到了解决方案。

      假设您想要捕捉任意数量的单词。

      “有四盏灯”

      “皮卡德船长是炸弹”

      您可能认为解决方案是:

      /((\w+)\s?)+/
      

      但这只会匹配整个输入字符串和最后捕获的组。

      你可以做的是使用“g”开关。

      那么,Perl 中的一个例子:

      use strict;
      use warnings;
      
      my $str1 = "there are four lights";
      my $str2 = "captain picard is the bomb";
      
      foreach ( $str1, $str2 ) {
          my @a = ( $_ =~ /(\w+)\s?/g );
          print "captured groups are: " . join( "|", @a ) . "\n";
      }
      

      输出是:

      captured groups are: there|are|four|lights
      captured groups are: captain|picard|is|the|bomb
      

      所以,如果您选择的语言支持“g”的等价物(我猜大多数人都这样做......),那么就有一个解决方案。

      希望这对和我处于同一位置的人有所帮助!

      S

      【讨论】:

        【解决方案3】:

        问题是所需的解决方案坚持使用捕获组。 C++ 提供了工具regex_token_iterator 来更好地处理这个问题(C++11 示例):

        #include <iostream>
        #include <string>
        #include <regex>
        
        using namespace std;
        
        int main() {
            std::regex e (R"((?:^-Numbers)?\s*(\d+))");
        
            string input;
        
            while (getline(cin, input)) {
                std::regex_token_iterator<std::string::iterator> a{
                    input.begin(), input.end(),
                    e, 1,
                    regex_constants::match_continuous
                };
        
                std::regex_token_iterator<std::string::iterator> end;
                while (a != end) {
                    cout << *a << " - ";
                    ++a;
                }
                cout << '\n';
            }
        
            return 0;
        }
        

        https://wandbox.org/permlink/TzVEqykXP1eYdo1c

        【讨论】:

        • 但是你在这个正则表达式示例中没有重复组
        猜你喜欢
        • 2019-02-11
        • 2011-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多