Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Regex atom with capturing groups #2

Open
tadfisher opened this issue May 8, 2023 · 0 comments
Open

Regex atom with capturing groups #2

tadfisher opened this issue May 8, 2023 · 0 comments

Comments

@tadfisher
Copy link

tadfisher commented May 8, 2023

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)
    )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant