0

I am trying to do a regex match with the following code:

std::wstring a1 = L"/key1 val1 /key2 val2 /key3 val3";
std::wregex re(L"\/[^\/]*");
std::wsmatch ws;

if (std::regex_match(a1, ws, re))
{
    //do something
}

I am expecting to see the following pair of matches:

/key1 val1

/key2 val2

/key3 val3

However, I am not seeing any match. Any idea why ?

If I try with L"/.+", then atleast I get a match of the whole string.

Thanks.

Ahsan
  • 2,964
  • 11
  • 53
  • 96

1 Answers1

1

Couple of things you are doing wrong.

  1. The problem is that std::regex_match must match the entire string but you are trying to match only part of it.

You need to either use std::regex_search or alter your regular expression to match all three parts at once:

  1. You are not required to escape slashes in c++.

Your regex should be std::wregex re(L"/[^/]*");

Final code

    std::wstring a1 = L"/key1 val1 /key2 val2 /key3 val3";
    std::wregex re(L"/[^/]*");
    std::wsmatch ws;
    
    while (std::regex_search(a1, ws, re)) {
      std::wcout << ws[0].str() << '\n';
      a1 = ws.suffix().str();
    }

Edit: Thanks to Heap underrun for much easy regex.

Rishabh Deep Singh
  • 807
  • 1
  • 12
  • 24
  • 1
    Also, there is no need to escape forward slashes `/` in C++ regex. So, the regular expression string could simply be `L"/[^/]*"` instead. – heap underrun May 03 '21 at 23:03
  • [`std::regex_iterator`](https://en.cppreference.com/w/cpp/regex/regex_iterator) might help too. – Jarod42 May 04 '21 at 08:49