Skip to content

Regex atom with capturing groups #2

@tadfisher

Description

@tadfisher

It would be nice to have a variant of regex() that returns the MatchResult to be able to use capturing groups. For example, I have this in our project:

private fun ParserState.match(pattern: Regex): MatchResult {
    val result = pattern.matchAt(input, position)
        ?: fail("Expected pattern '$pattern', but there was no match.")
    position += result.value.length
    return result
}

This is handy in combination with map, or inline, using destructuring:

private val date: Parser<LocalDate> = parser {
    val (y, m, d) = match(Regex("""(\d{4})(\d{2})(\d{2})""")).destructured
    LocalDate(
        year = y.toInt().between(0..9999),
        monthNumber = m.toInt().between(1..12),
        dayOfMonth = d.toInt().between(1..31)
    )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions