我的正则表达式有什么问题?

时间:2022-01-03 03:14:49
#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main(){
  regex rule("(?<test>\\d+)");
  string str = "11.22.33.44";
  boost::smatch result;
  string::const_iterator start = str.begin();
  string::const_iterator end = str.end();
  while (regex_search(start, end, result, rule))
    {
     std::cout << result['test'].str() << std::endl;// here 
     start = result['test'].second;// it seems it work 
    }
  getchar();
  return 0;
}

Why it didn't work correctly? I'm used to using PHP to do that. How can I make my code work? the aim of the code is to match the each number in the regex named group.

为什么它不能正常工作?我习惯使用PHP来做到这一点。如何使我的代码工作?代码的目的是匹配正则表达式命名组中的每个数字。

1 个解决方案

#1


1  

'test' is a character literal. You want to use a string literal: use "test"

'test'是一个字符文字。你想使用字符串文字:使用“测试”

Besides, use compiler warnings:

此外,使用编译器警告:

test.cpp|13 col 29| warning: multi-character character constant [-Wmultichar]
||          std::cout << result['test'].str() << std::endl; // here

DEMO

Live On Coliru

住在科利鲁

#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main() {
    regex rule("(?<test>\\d+)");
    string str = "11.22.33.44";
    boost::smatch result;
    string::const_iterator start = str.begin();
    string::const_iterator end = str.end();
    while (regex_search(start, end, result, rule)) {
        std::cout << result["test"].str() << std::endl;
        start = result["test"].second;
    }
}

Prints

打印

11
22
33
44

#1


1  

'test' is a character literal. You want to use a string literal: use "test"

'test'是一个字符文字。你想使用字符串文字:使用“测试”

Besides, use compiler warnings:

此外,使用编译器警告:

test.cpp|13 col 29| warning: multi-character character constant [-Wmultichar]
||          std::cout << result['test'].str() << std::endl; // here

DEMO

Live On Coliru

住在科利鲁

#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main() {
    regex rule("(?<test>\\d+)");
    string str = "11.22.33.44";
    boost::smatch result;
    string::const_iterator start = str.begin();
    string::const_iterator end = str.end();
    while (regex_search(start, end, result, rule)) {
        std::cout << result["test"].str() << std::endl;
        start = result["test"].second;
    }
}

Prints

打印

11
22
33
44