正则表达式用于匹配子表达式

时间:2019-05-10 19:09:14

标签: c++ regex regex-group

当我使用

这样的正则表达式时
std::regex midiNoteNameRegex("([cdefgab])([b#]{0,1})([0-9]))|([0-9]{3})|([A-Z0-9]{2})");

通过“ |”连接的三个顶级子表达式以哪种模式匹配。 有没有办法告诉哪个?除了一个接一个地测试它们之外?

如果我使用命名子表达式会很容易,但是C ++中没有命名子表达式。

如何解决此问题?

2 个答案:

答案 0 :(得分:2)

鉴于正则表达式中的组,这只是对匹配对象的简单搜索,
在C ++中是一个标志(int)检查,没有明显的开销。

wregex MyRx = wregex( "([cdefgab])([b#]{0,1})([0-9])|([0-9]{3})|([A-Z0-9]{2})", 0);

wstring::const_iterator start = str.begin();
wstring::const_iterator end   = str.end();
wsmatch m;

while ( regex_search( start, end, m, MyRx ) )
{
    if ( m[1].matched )       
        // First alternation
    else
    if ( m[4].matched )       
        // Second alternation
    else
    if ( m[5].matched )       
        // Third alternation
    start = m[0].second;
}

以及可能的用法

<input name="ctl00$ctl00$placeContent$placeTopContent$filter$textAccount" type="text" value="110111102" id="ctl00_ctl00_placeContent_placeTopContent_filter_textAccount" style="width: 130px;" data-kpxc-id="ctl00_ctl00_placeContent_placeTopContent_filter_textAccount" tabindex="-1">

答案 1 :(得分:0)

我没有确切的答案,但我相信答案很可能不是。

命名捕获组不是必需的功能:http://www.cplusplus.com/reference/regex/ECMAScript/

命名捕获组的实现可能并非易事,并且可能降低正则表达式引擎的性能。

在此问题上找到了另一篇我同意的信息:C++ regex: Which group matched?