字符串\ 0时如何匹配结果?

时间:2019-04-15 12:06:00

标签: java c++ regex

C ++中的字符串匹配无法获得正确的结果,但是在Java中可以 Java代码如下

       String txt = "  static char k_a123[] =  \"fefeffefefwefwef/fefe/f/ef/ef\\0\"; int fefefefefeeffef = 123;     static char k_a123233[] =  \"fef/efef/efef\\0\";     int fwefnewff=21323;     static char k_a1233334[] =  \"<init>\\0\";     static char k_a123555[] =  \"fefefef)fefe/fef/V\\0\";     addAll(123,333);";
       String reg = "\\sstatic\\schar\\sk_\\S+\\s=";
       Pattern p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
       Matcher m = p.matcher(txt);
       while (m.find()) {
           for (int i = 0; i <= m.groupCount(); i++) {
               System.out.println(" ===== " + m.group(i));
           }
       }
// fowllow is outpu result
// =====  static char k_a123[] =
// =====  static char k_a123233[] =
// =====  static char k_a1233334[] =
// =====  static char k_a123555[] =

C ++代码如下

    std::string s1 = "  static char k_a123[] =  \"fefeffefefwefwef/fefe/f/ef/ef\\0\"; int fefefefefeeffef = 123;     static char k_a123233[] =  \"fef/efef/efef\\0\";     int fwefnewff=21323;     static char k_a1233334[] =  \"<init>\\0\";     static char k_a123555[] =  \"fefefef)fefe/fef/V\\0\";     addAll(123,333);";

    std::string reee = "\\sstatic\\schar\\sk_\\S+\\s="; // Double Quote String 4
    std::string xxx(reee);

    std::regex rgx(xxx);

    std::smatch match;
    std::regex_search(s1, match, rgx);
    for (uint32_t index = 0; index < match.size(); index++)
    {
        printf("bbb [%d]  %s\n", index, std::string(match[index]).c_str());
    }
// xcode output
// bbbb [0]   static char k_v1[] =
// bbbb [1]  
/********* xcode output over ,nothing...... why?   *******************/

我认为这是因为c ++使用\ 0截断字符串,而java匹配了正确的结果。 C ++使用xcode运行代码 如何为Java和C ++获得相同的结果?

这两部分代码可以复制并直接运行,但是Java输出正确。 C ++不正确。如何使它们输出相同的结果。

1 个答案:

答案 0 :(得分:0)

感谢:DanM。

关注是答案

How to match multiple results using std::regex

 std::string s1 = "  static char k_a123[] =  \"fefeffefefwefwef/fefe/f/ef/ef\\0\"; int fefefefefeeffef = 123;     static char k_a123233[] =  \"fef/efef/efef\\0\";     int fwefnewff=21323;     static char k_a1233334[] =  \"<init>\\0\";     static char k_a123555[] =  \"fefefef)fefe/fef/V\\0\";     addAll(123,333);";

    std::string rrr = "\\sstatic\\schar\\sk_\\S+\\s=\\s(.*?);";
    std::regex r(rrr);
    const std::sregex_token_iterator end;
    for (std::sregex_token_iterator i(s1.cbegin(), s1.cend(), r, 1); i != end; ++i) {
        cout <<"\n ----- " << *i << endl;
    }
    cout << "====" << endl;


  [1]: http://how-to-match-multiple-results-using-stdregex