简体   繁体   中英

Why does regex work well in java, but does not work in c++?

using c++

    std::regex reg("[\\s\\S]*abc[\\s\\S]*:(\\S+)");
    std::string src = "    abc-def gg, :OK";
    std::smatch match;
    bool flag = std::regex_search(src, match, reg);
    // flag is false 

using java

        Pattern p = Pattern.compile("[\\s\\S]*abc[\\s\\S]*:(\\S+)");
        String src = "    abc-def gg, :OK";
        Matcher m = p.matcher(src);
        int num = 0;
        while (m.find()) {
            for (int i = 1; i <= m.groupCount(); i++) {
                num++;
            }
        }
        System.out.println(num);  num is 1 ,work well

In the above two code examples, The C++ code does not output the correct result, but the java code creates the correct result. Why is this happening, where is the problem?

You are correct. Your example does not work on Mac OS. I run into the same problem if I run it on a Mac.

Your final comment asked "how make it working in MAC OS,pls", which I am guessing is asking for the code to make this work on a Mac rather than asking why two regex implementations produce different results. That is a much easier solution:

This works on my mac:

#include <iostream>
#include <regex>
#include <string>
using namespace std;

int main() {
//  std::regex reg("[\\s\\S]*abc[\\s\\S]*:(\\S+)");
  std::regex reg("[\\s\\S]*abc.*:(\\S+)");
  std::string src = "    abc-def gg, :OK";
  std::smatch match;
  bool flag = std::regex_search(src, match, reg);
  std::cout << flag;
  return 0;
}

The same expression that works on regex101.com, does not work on the Mac (llvm). It seems that the [\s\S] does not work well using Mac's regex library, but that can be solved by replacing the [\s\S] with .* .

In response to a further query to isolate the 'OK' portion of the string, that is done using groups. The group[0] is always the entire match. group[1] is the next portion appears between parentheses (...)

This code illustrates how to extract the two groups.

#include <iostream>
#include <regex>
#include <string>
using namespace std;

std::string GetMatch() {
  //  std::regex reg("[\\s\\S]*abc[\\s\\S]*:(\\S+)");
  std::regex reg("[\\s\\S]*abc.*:(\\S+)");
  std::string src = "    abc-def gg, :OK";
  std::smatch matches;
  bool flag = std::regex_search(src, matches, reg);
  std::cout << flag;

  for(size_t i=0; i<matches.size(); ++i) {
    cout << "MATCH: " << matches[i] << endl;
  }

  return matches[1];
}

int main() {
  std::string result = GetMatch();

//  match
  cout << "The result is " << result << endl;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM