Home > OS >  Regex not able to show chars after space
Regex not able to show chars after space

Time:07-20

I want to break this string into two parts

{[data1]name=NAME1}{[data2]name=NAME2}

1) {[data1]name=NAME1}
2){[data2]name=NAME2}

I am using Regex to attain this and this works fine with the above string , but if i add space to the name then the regex does not take characters after the space.

{[data1]name=NAME 1}{[data2]name=NAME 2}

In this string it breaks only till NAME and does not show the 1 and 2 chars

This is my code

    std::string stdstrData = "{[data1]name=NAME1}{[data2]name=NAME2}"
    std::vector<std::string> commandSplitUnderScore;
    std::regex re("\\}");
        std::sregex_token_iterator iter(stdstrData.begin(), stdstrData.end(), re, -1);
        std::sregex_token_iterator end;
    
        while (iter != end) {
            if (iter->length()) {
                commandSplitUnderScore.push_back(*iter);
            }
              iter;
        }
    
    
    for (auto& str : commandSplitUnderScore) {
        std::cout << str << std::endl;
    }

CodePudding user response:

A good place to start is to use regex101.com and debug your regex before putting it into your c code. e.g. https://regex101.com/r/ID6OSj/1 (don't forget to escape your C string properly when copying the regex you made on that site). Example :

#include <iostream>
#include <string>
#include <regex>


int main()
{
    std::string input{ "{[data]name=NAME1}{[data]name=NAME2}" };
    std::regex  rx{ "(\\{\\[data\\].*?\\})(\\{\\[data\\].*?\\})" };
    std::smatch match;

    if (std::regex_match(input, match, rx))
    {
        std::cout << match[1] << "\n"; // match[1] is first group
        std::cout << match[2] << "\n"; // match[2] is second group
    }

    return 0;
}
  • Related