请问能否使用JavaScript(ECMAScript)正则表达式在C++11中提取冒号和插入符号之间的文本?我不需要捕获
我尝试使用以下正则表达式:
这里是贴在live coliru上的代码。它展示了我尝试解决这个问题的方式,但是我只得到了1个匹配结果。我需要知道如何提取之前所述的对应于p m或u字符的每个潜在的3个匹配结果。
上面的程序输出如下:
hw-descriptor
本身,但必须确保该行中存在hw-descriptor
以便查找后续匹配项。此外,:p....^
、:m....^
和:u....^
可以按任意顺序出现,并且至少要有一个存在。我尝试使用以下正则表达式:
static const std::regex gRegex("(?:hw-descriptor)(:[pmu](.*?)\\^)+", std::regex::icase);
针对以下文本行:
"hw-descriptor:pTEXT1^:mTEXT2^:uTEXT3^"
这里是贴在live coliru上的代码。它展示了我尝试解决这个问题的方式,但是我只得到了1个匹配结果。我需要知道如何提取之前所述的对应于p m或u字符的每个潜在的3个匹配结果。
#include <iostream>
#include <string>
#include <vector>
#include <regex>
int main()
{
static const std::regex gRegex("(?:hw-descriptor)(:[pmu](.*?)\\^)+", std::regex::icase);
std::string foo = "hw-descriptor:pTEXT1^:mTEXT2^:uTEXT3^";
// I seem to only get 1 match here, I was expecting
// to loop through each of the matches, looks like I need something like
// a pcre global option but I don't know how.
std::for_each(std::sregex_iterator(foo.cbegin(), foo.cend(), gRegex), std::sregex_iterator(),
[&](const auto& rMatch) {
for (int i=0; i< static_cast<int>(rMatch.size()); ++i) {
std::cout << rMatch[i] << std::endl;
}
});
}
上面的程序输出如下:
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
hw-descriptor:pTEXT1^:mTEXT2^:uTEXT3^
:uTEXT3^
TEXT3
^(?:hw-descriptor)(.*?:[pmu]\^.*)
,第二步:([pmu])(.*?)\^
,第二步使用第一步的捕获缓冲区作为目标字符串,并进行全局操作。 - user557597\G
的正则表达式,甚至可以访问捕获集合(参见 http://www.boost.org/doc/libs/1_33_1/libs/regex/doc/captures.html)。 - Wiktor Stribiżew