我使用的是C ++ TR1 ::与ECMA正则表达式语法正则表达式。 我正在试图做的是分析一个头,并返回头中具有的每个项目关联的值。
标题:
-Testing some text
-Numbers 1 2 5
-MoreStuff some more text
-Numbers 1 10
我想这样做的是找到所有“ - 值”行,并把每个数字变成自己的结果与一个单一的正则表达式。 正如你所看到的,“ - 值”行可以有上线值的任意数字。 目前,我只是在寻找“ - 值([\ s0-9] +)”,然后符号化这一结果。 我只是想知道是否有任何的方式来寻找并在一个单一的正则表达式记号化的结果。
我要问这个确切的同样的问题,而且我有种找到了解决办法。
比方说,你有你想要捕捉的话任意数量。
“有四盏灯”
和
“船长皮卡德是炸弹”
你可能会认为,解决的办法是:
/((\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”等效(我猜大多数人...)。
希望这可以帮助别人谁是在相同的位置上我!
小号
的问题是,所需的溶液坚持使用捕获基团。 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
文章来源: Is there a way to have a capture repeat an arbitrary number of times in a regex?