Получите группы регулярных выражений с помощью Vavr

Учитывая, что Vavr предоставляет кортежи, можно ли использовать их для захват групп в регулярных выражениях?

Взяв строку HTTP-запроса в качестве примера строки для соответствия

ПОЛУЧИТЬ /ресурс HTTP 1.1

и соответствующий шаблон

Pattern.compile("(\\w+) (.+) (.+)")

Существуют ли в Vavr методы, которые возвращают три совпадающие строки в виде кортежа?


person Matthias Braun    schedule 02.07.2019    source источник


Ответы (1)


Это легко создать самостоятельно:

/**
 * Gets the three matched groups of the {@code regex} from the {@code original}.
 *
 * @param regex    a {@link Pattern} that should have three groups in it and
                   match the {@code original}
 * @param original the string we'll match with the {@code regex}
 * @return a {@link Tuple3} of the three matched groups or {@link Option#none} if
 *         the {@code regex} did not match
 */
static Option<Tuple3<String, String, String>> getGroups3(Pattern regex,
                                                         CharSequence original) {
    var matcher = regex.matcher(original);
    return matcher.matches() && matcher.groupCount() == 3 ?
            Some(Tuple.of(matcher.group(1), matcher.group(2), matcher.group(3))) :
            Option.none();
}

Вот как вы можете использовать метод:

var pattern = Pattern.compile("(\\w+) (.+) (.+)");
var requestLine = "GET /resource HTTP 1.1";

var result = getGroups3(pattern, requestLine).fold(
        // No match
        () -> String.format("Could not parse request method, resource, and " +
                        "HTTP version from request line. Request line is '%s'",
                requestLine),
        // Do whatever you want with the three matched strings
        tuple3 -> tuple3.apply((method, resource, httpVersion) ->
                String.format("Method is %s, resource is %s, HTTP version is %s",
                        method, resource, httpVersion)));
person Matthias Braun    schedule 02.07.2019