Regex tr1::正则表达式正则表达式搜索问题
我正在使用tr1::regex尝试从字符串中提取一些匹配项。示例字符串可以是Regex tr1::正则表达式正则表达式搜索问题,regex,search,matching,tr1,Regex,Search,Matching,Tr1,我正在使用tr1::regex尝试从字符串中提取一些匹配项。示例字符串可以是 asdf werq "one two three" asdf 我想从中解脱出来: asdf werq one two three asdf 由于引号中的内容组合在一起,所以我尝试使用正则表达式\“(.+?)\”|([^\\s]+)。我使用的代码是: cmatch res; regex reg("\"(.+?)\"|([^\\s]+)", regex_constants::icase); regex_
asdf werq "one two three" asdf
我想从中解脱出来:
asdf
werq
one two three
asdf
由于引号中的内容组合在一起,所以我尝试使用正则表达式\“(.+?)\”|([^\\s]+)
。我使用的代码是:
cmatch res;
regex reg("\"(.+?)\"|([^\\s]+)", regex_constants::icase);
regex_search("asdf werq \"one two three\" asdf", res, reg);
cout << res.size() << endl;
for (unsigned int i = 0; i < res.size(); ++k) {
cout << res[i] << endl;
}
我做错了什么?您可以尝试以下正则表达式:
(?<=")[^"]*(?=")|[^"\s]\S*
(?您的正则表达式引擎似乎不支持lookbehind断言。要避免使用lookbehind,您可以尝试以下操作:
"([^"]*)"|(\S+)
或引用:
"\"([^\"]*)\"|(\\S+)"
这个正则表达式可以工作,但每个匹配项都有两个捕获,其中一个捕获为空(第一个捕获是非引号的单词,第二个捕获是引号的字符串)
为了能够使用它,您需要迭代所有匹配,并为每个匹配使用非空捕获
我对TR1的了解不够,所以我不知道如何迭代所有匹配项。但如果我没有弄错的话,res.size()
将始终等于3
例如,对于字符串asdf“一二三”werq
,第一个匹配将是:
res[0] = "asdf" // the entire match
res[1] = "" // the first capture
res[2] = "asdf" // the second capture
res[0] = "\"one two three\"" // the entire match including leading/trailing quotes
res[1] = "one two three" // the first capture
res[2] = "" // the second capture
res[0] = "werq" // the entire match
res[1] = "" // the first capture
res[2] = "werq" // the second capture
第二场比赛将是:
res[0] = "asdf" // the entire match
res[1] = "" // the first capture
res[2] = "asdf" // the second capture
res[0] = "\"one two three\"" // the entire match including leading/trailing quotes
res[1] = "one two three" // the first capture
res[2] = "" // the second capture
res[0] = "werq" // the entire match
res[1] = "" // the first capture
res[2] = "werq" // the second capture
第三场比赛是:
res[0] = "asdf" // the entire match
res[1] = "" // the first capture
res[2] = "asdf" // the second capture
res[0] = "\"one two three\"" // the entire match including leading/trailing quotes
res[1] = "one two three" // the first capture
res[2] = "" // the second capture
res[0] = "werq" // the entire match
res[1] = "" // the first capture
res[2] = "werq" // the second capture
HTH.实际上,当我使用该正则表达式时,当我运行该程序时,会将其输出到控制台:“此应用程序已请求运行时以异常方式终止它。请联系…”诸如此类,它崩溃了。我没有一个工作环境可以检查这一点,但我已经用Java和C测试了正则表达式,它也没有崩溃。请使用syntax_option_type=extended确保它遵循扩展正则表达式的标准语法。(顺便说一句,我对正则表达式的第一部分做了一个小的修改,以防止它在引用的单词结束后捕获一个空格。)这里邀请您使用正则表达式:我将其更改为正则表达式reg((?Wierd error:无论我使用什么正则表达式,正则表达式常量::语法选项类型::扩展总是使它崩溃。如果我去掉它并删除(?如果我使用迭代器,那么我将如何获得你所说的匹配项呢?你使用的迭代器的样式为for(std::tr1::sregex_token_iterator I(str.begin(),str.end(),reg);I!=end;++I){cout以下是什么:for(std::tr1::sregex_token_迭代器I(str.begin(),str.end(),reg);I!=end;++I){cout