I need a regular expression that captures an argument between parentheses. Billets before and after the argument must not be captured. For example, "( ab & c )" should return "ab & c" . The argument can be enclosed in single quotes if leading or trailing spaces are needed. So, "( ' ab & c ' )" should return " ab & c " .
wstring String = L"( ' ab & c ' )"; wsmatch Matches; regex_match( String, Matches, wregex(L"\\(\\s*(?:'(.+)'|(.+?))\\s*\\)") ); wcout << L"<" + Matches[1].str() + L"> " + L"<" + Matches[2].str() + L">" + L"\n"; // Results in "<> < ' ab & c '>", not OK
The second alternative seems to fit, but it also took up space before the first quote! It should have been caught \s after opening the parenthesis.
Removing the second alternative:
regex_match( String, Matches, wregex(L"\\(\\s*(?:'(.+)')\\s*\\)") ); wcout << L"<" + Matches[1].str() + L">" + L"\n"; // Results in "< ab & c >", OK
Creating an alternate capture group:
regex_match( String, Matches, wregex(L"\\(\\s*('(.+)'|(.+?))\\s*\\)") ); wcout << L"<" + Matches[1].str() + L"> " + L"<" + Matches[2].str() + L"> " + L"<" + Matches[3].str() + L">" + L"\n"; // Results in "<' ab & c '> < ab & c > <> ", OK
Am I not noticing anything?
source share