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


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;
}

3

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