OCaml`Str`模块的正则表达式匹配的奇数结果

问题描述 投票:0回答:1

当我执行以下测试程序时:

let re = Str.regexp "{\\(foo\\)\\(bar\\)?}"

let check s =
    try
        let n = Str.search_forward re s 0 in
        let a = Str.matched_group 1 s in
        let b = Str.matched_group 2 s in
        Printf.printf "'%s' => n=%d, a='%s', b='%s'\n" s n a b
    with
        _ -> Printf.printf "'%s' => not found\n" s

let _ =
    check "{foo}";
    check "{foobar}"

我得到奇怪的结果。即:

$ ocaml str.cma test.ml'{foo}'=>找不到'{foobar}'=> n = 0,a ='foo',b ='bar'

通过\\(\\)进行分组是否与?运算符不兼容?文档未提及此。

regex ocaml
1个回答
0
投票

对于您的第一个示例,组2不匹配。因此对Str.matched_group 2的调用引发了Not_found

我这样重写了您的check函数:

let check s =
    let check1 n g =
        try
            let m = Str.matched_group g s in
            Printf.printf "'%s' group %d => n = %d, match = '%s'\n"
                s g n m
        with Not_found ->
            Printf.printf "'%s' group %d => not matched\n" s g
    in
    let n = Str.search_forward re s 0 in
    check1 n 1;
    check1 n 2

以下是修改后的代码的输出:

'{foo}' group 1 => n = 0, match = 'foo'
'{foo}' group 2 => not matched
'{foobar}' group 1 => n = 0, match = 'foo'
'{foobar}' group 2 => n = 0, match = 'bar'
© www.soinside.com 2019 - 2024. All rights reserved.