sohel14_cse_ju
sohel14_cse_ju

Reputation: 2521

Regex only matched part in matches

I am expecting to get only the matched part of a line. my expression looks like :

std::wstring strPatternDat = L"DECL\\s+E6POS\\s+X[A-Za-z0-9]+=\\{X\\s-?[1-9]\\d*(\\.\\d+)+,Y\\s-?-?[1-9]\\d*(\\.\\d+)+,Z\\s-?-?[1-9]\\d*(\\.\\d+)+,A\\s-?-?[1-9]\\d*(\\.\\d+)+,B\\s-?-?[1-9]\\d*(\\.\\d+)+,C\\s-?-?[1-9]\\d*(\\.\\d+)"

Line I am searching on :

DECL E6POS XB1={X 152.115494,Y -1553.65002,Z 1255.94604,A 162.798798,B -3.58411908,C -176.614395,S 6,T 50,E1 -4949.979,E2 0.0,E3 0.0,E4 0.0,E5 0.0,E6 0.0}

Finding match as :

    if (regex_match(line, matchesDat, expressionDat))
    {
        TRACE("Match found");
    }

In the matched data matchesDat i am getting full matched line. But i am expecting only the matched part

Getting :

DECL E6POS XB1={X 152.115494,Y -1553.65002,Z 1255.94604,A 162.798798,B -3.58411908,C -176.614395,S 6,T 50,E1 -4949.979,E2 0.0,E3 0.0,E4 0.0,E5 0.0,E6 0.0}

Expecting :

DECL E6POS XB1={X 152.115494,Y -1553.65002,Z 1255.94604,A 162.798798,B -3.58411908,C -176.614395,

How can i get only matched part not the full line ?

Upvotes: 1

Views: 72

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

You need to use regex_search and then get the matched value as the result, not the whole string:

std::wstring expressionDat = L"DECL\\s+E6POS\\s+X[A-Za-z0-9]+=\\{X\\s-?[1-9]\\d*(\\.\\d+)+,Y\\s-?-?[1-9]\\d*(\\.\\d+)+,Z\\s-?-?[1-9]\\d*(\\.\\d+)+,A\\s-?-?[1-9]\\d*(\\.\\d+)+,B\\s-?-?[1-9]\\d*(\\.\\d+)+,C\\s-?-?[1-9]\\d*(\\.\\d+)";
std::wstring line(L"DECL E6POS XB1={X 152.115494,Y -1553.65002,Z 1255.94604,A 162.798798,B -3.58411908,C -176.614395,S 6,T 50,E1 -4949.979,E2 0.0,E3 0.0,E4 0.0,E5 0.0,E6 0.0}");
wsmatch matchesDat;
if (std::regex_search(line, matchesDat, wregex(expressionDat)))
{
    std::wcout << L"Match found: " + matchesDat.str() << "\nSuffix: " << matchesDat.suffix().str();
}

enter image description here

The matchesDat.suffix() will output the rest of the string after the match.

Upvotes: 1

Related Questions