Skip to content

Captures<'t> .at, .name return "" to represent both "matches empty string" and "no match" #14602

Closed
@emk

Description

@emk

The methods at and name on Captures<'t> return "" to represent both failed matches and successful matches against the empty string. In the case of at, a programmer can use pos to distinguish between the two situations. But in the case of name, there's no good, public API which allows us to test for a match.

The follow regex has two named matched groups, key and value. value is optional:

// Matches "foo", "foo;v=bar" and "foo;v=".
regex!(r"(?P<key>[a-z]+)(;v=(?P<value>[a-z]*))?");

We can access value using caps.name("value"), but there's no way for us to distinguish between the "foo" and "foo;v=" cases.

Even if we're willing to treat both meanings of "" as "failed match", it's still a nuisance to convert them to Option:

fn name<'t>(caps: &Captures<'t>, name: &str) -> Option<&'t str> {
    let s = caps.name(name);
    if s == "" { None } else { Some(s) }
}

Now, I don't know whether it would be better to modify at and name to return Option, or add new at_opt and name_opt functions. But at the very least, there should be some convenient way to distinguish between the cases "foo" and "foo;v=".

This would be relatively easy to implement, because Captures uses Option internally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions