Search code examples
vala

GLib.Regex escape chars


I created a Regex("/^(0x[0-9a-fA-F]+\\s*)\"/") for data "0x7fffffffe956 \"foobar\"", expecting to match on "0x7fffffffe956 \""

This format /^(0x[0-9a-fA-F]+\s*)\"/ works on regex101.com. I can not get a similar GLib.Regex to work. Here is a quick test to illustrate the problem.

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");
        }
    }

My test results keep failing:

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]

Other than the requirement to prefix all escape chars with a '\', what am I not seeing?


Solution

  • You shouldn't include the initial and trailing /. If those are included in the quotes, they are assumed to be part of the regular expression.