GLib.Regex 转义字符

GLib.Regex escape chars

我为数据“0x7fffffffe956 \"foobar\"”创建了一个 Regex("/^(0x[0-9a-fA-F]+\\s*)\"/"),期望匹配关于“0x7fffffffe956 \”

此格式 /^(0x[0-9a-fA-F]+\s*)\"/ 适用于 regex101.com。我无法使用类似的 GLib.Regex。这是一个快速测试来说明问题。

public void test_regex() {
    //REFER:https://developer.gnome.org/glib/stable/glib-regex-syntax.html

    try {
        GLib.MatchInfo mi;
        int start_pos;
        int end_pos;
        string test_str="0x7fffffffe956 \"foobar\"";
        Regex _regex=new Regex("/^(0x[0-9a-fA-F]+\s*)\"/");
        bool bResult=_regex.match(test_str, 0, out mi);
        expect(bResult==true,"%s match result[%s]",test_str,bResult.to_string());
        if (bResult){
            bResult=mi.fetch_pos(1, out start_pos, out end_pos);
            expect ( bResult,"mi.fetch_pos(1) result[%s] start_pos[%d] end_pos[%d]",bResult.to_string(),start_pos,  end_pos);
            }
        }
    catch(Error e) {
        catch_exception(e, "test_regex");
        }
    }

我的测试结果一直失败:

UT_TestSuite start
GTest: run: /UTGdbExpansion
DBUG UT_Main.vala:90: Running test:Test Regex strings
DBUG UT_Main.vala:41: expect:UT_GdbExpansion.vala:71: 07fffffffe956 "foobar" match result[false] result[false]

除了要求在所有转义字符前加上“\”,我还没有看到什么?

您不应包括首字母和尾随 /。如果这些包含在引号中,则假定它们是正则表达式的一部分。